无效的JSON,意外的令牌

时间:2015-09-28 06:32:36

标签: javascript json angularjs

我尝试使用angular将JSON数据发送到服务器,但是在firefox中获取JSON.parse错误并在chrome中获取Unexpected标记。

它有时可以工作并且有时会抛出错误。

我认为这是因为我用来创建一些密钥的时间戳。

{
    "genericformfieldId": "1",
    "userId": "2",
    "formData": {
        "_1443551400000": [
            {
                "mValue": "HARYANA",
                "type": "DropDown",
                "name": "selectState"
            }
        ],
        "_1443637800000": [
            {
                "mValue": "CHHATTISGARH",
                "type": "DropDown",
                "name": "selectState"
            }
        ],
        "_1443810600000": [
            {
                "mValue": "sac",
                "type": "SingleLineText",
                "name": "departureFrom"
            }
        ]
    }
}

请建议。

添加发布数据的代码

$http({
    method: 'POST',
    url:    Url, 
    headers: { "Content-Type": "application/json" }, 
    data: formData
    })
.success( function( response, status, headers, config ) {
    console.log( response );
    if( response ) {                    
        deferred.resolve( response );
    }
})
.error( function( response, status, headers, config ) {  
    deferred.reject( null );
});

2 个答案:

答案 0 :(得分:1)

如果你JSON.parse一个对象"意外的标记o"抛出只是因为你试图解析object.toString(),即[object Object]。尝试JSON.parse('[object Object]'); ;)

这应该对你有用

var data = '{
    "genericformfieldId": "1",
    "userId": "2",
    "formData": {
        "_1443551400000": [
            {
                "mValue": "HARYANA",
                "type": "DropDown",
                "name": "selectState"
            }
        ],
        "_1443637800000": [
            {
                "mValue": "CHHATTISGARH",
                "type": "DropDown",
                "name": "selectState"
            }
        ],
        "_1443810600000": [
            {
                "mValue": "sac",
                "type": "SingleLineText",
                "name": "departureFrom"
            }
        ]
    }
}';
JSON.parse(data);

这个答案https://stackoverflow.com/a/12719860/1868660解释道 Unexpected token ILLEGAL(…)问题

答案 1 :(得分:0)

你必须清理输入json。

检查一下:

https://jsfiddle.net/am190cv5/

这是来源:

var s = '{"genericformfieldId": "1","userId": "2","formData": {"_1443551400000": [{"mValue": "HARYANA","type": "DropDown","name": "selectState"}],"_1443637800000": [{"mValue": "CHHATTISGARH","type": "DropDown","name": "selectState"}],"_1443810600000": [{"mValue": "sac","type": "SingleLineText","name": "departureFrom"}]}}';

var result = JSON.parse(s);
console.log(result);

打开控制台并查看结果。