简体   繁体   English

json错误:SyntaxError:JSON.parse:意外字符

[英]json error: SyntaxError: JSON.parse: unexpected character

I have some problem. 我有问题 When I try post json object, I have error: error: SyntaxError: JSON.parse: unexpected character 当我尝试发布json对象时,出现错误:错误: 语法错误:JSON.parse:意外字符

My javascript object: 我的JavaScript对象:

var $arr_data = {
        title: '',
        category: '',
        about: '',
        sex: 'unisex',
        accessories: 'no',
        quantity: []
    };

I think that a problem are in this function: 我认为此功能存在问题:

  function data_quantity($size_input,$quant_input)
    {
        var $string = "{color:'"+$pattern+"',size:'"+$size_input+"',quantity:'"+$quant_input+"'}";
        $arr_data.quantity.push($string);
    }

alert(JSON.stringify($arr_data)); returns the following string: 返回以下字符串:

{
"title":"title_test",
"category":"3",
"about":"about_test",
"sex":"woman",
"accessories":"no",
"quantity":[
    "{color:'none',size:'xxl',quantity:'5'}",
    "{color:'black',size:'xxl',quantity:'1'}",
    "{color:'white',size:'s',quantity:'9'}"
    ]
}

You should add an object instead of a JSON string to your array: 您应该在数组中添加一个对象而不是JSON字符串:

var $string = {
    color: $pattern, 
    size: $size_input,
    quantity: $quant_input
};

You are mixing javascript objects with a JSON string. 您正在将javascript对象与JSON字符串混合。 With JSON.stringify your object will then be converted to a string. 使用JSON.stringify您的对象将被转换为字符串。

Also just as a sidenote, why are you adding the $ prefix to all your variables? 同样作为一个旁注,为什么要在所有变量中添加$前缀? This is javascript not php, so no need for that. 这是JavaScript而不是php,因此无需这样做。 You can maybe use it for marking jQuery objects but doesn't really make sense with normal variables. 您也许可以将其用于标记jQuery对象,但对于普通变量而言实际上没有任何意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM