【问题标题】:json error: SyntaxError: JSON.parse: unexpected characterjson 错误:SyntaxError:JSON.parse:意外字符
【发布时间】:2014-01-13 15:10:12
【问题描述】:

我有一些问题。当我尝试发布 json 对象时,出现错误:错误:SyntaxError: JSON.parse: unexpected character

我的 javascript 对象:

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

我认为这个函数有问题:

  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)); 返回以下字符串:

{
"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'}"
    ]
}

【问题讨论】:

  • $pattern 来自哪里(在data_quantity 函数中)?

标签: javascript jquery json


【解决方案1】:

您应该在数组中添加一个对象而不是 JSON 字符串:

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

您正在将 javascript 对象与 JSON 字符串混合。使用JSON.stringify,您的对象将被转换为字符串。

另外,作为旁注,为什么要在所有变量中添加 $ 前缀?这是 javascript 而不是 php,所以不需要。您也许可以使用它来标记 jQuery 对象,但对于普通变量并没有真正意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2013-09-14
    • 2014-06-27
    相关资源
    最近更新 更多