开发者

Problem parsing JSON

I encounter problems tring to consume a third party web servive in JSON format. The JSON response from the server kinda looks like this:

{
    "ID":10079,
    "DateTime":new Date(1288384200000),
    "TimeZoneID":"W. Europe Standard Time",
    "groupID":284,
    "groupOrderID":10
}

I use JavaScript with no additional libs to parse the JSON.

//Parse JSON string to JS Object            
var messageAsJSObj = JSON.parse(fullResultJSON);

The parsing fails. A JSON validatior tells me, "new Date(1288384200000)" is not valid.

Is开发者_开发知识库 there a library which could help me parse the JSON string?


Like others have pointed out, it's invalid JSON. One solution is to use eval() instead of JSON.parse() but that leaves you with a potential security issue instead.

A better approach might be to search for and replace these offending issues, turning the data into valid JSON:

fullResultJSON = fullResultJSON.replace(/new Date\((\d+)\)/g, '$1');

You can even go one step further and "revive" these fields into JavaScript Date objects using the second argument for JSON.parse():

var messageAsJSObj = JSON.parse(fullResultJSON, function (key, value) {
    if (key == "DateTime")
        return new Date(value);

    return value;
}); 

Here's an example: http://jsfiddle.net/AndyE/vcXnE/


Your example is not valid JSON, since JSON is a data exchange technology. You can turn your example into a Javascript object using eval:

var almostJSON = "{
    "ID":10079,
    "DateTime":new Date(1288384200000),
    "TimeZoneID":"W. Europe Standard Time",
    "groupID":284,
    "groupOrderID":10,
}";

and then evaling it:

var myObject = eval('(' + almostJSON + ')');

Then, myObject should hold what you're looking for.

Note that functions are not allowed in JSON because that could compromise security.


try var obj = eval('(' + fullResultJSON + ')'); and you'll have the object like Pekka said. Don't forget to use the extra '()' though. And indeed json should have both property and value enclosed in quotes.


Parsing fails because all you can parse in a json object are null, strings, numbers, objects, arrays and boolean values so new Date(1288384200000), cannot be parsed

You have also another problem, last property shouldn't have the trailing comma.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜