开发者

How can I interpret a JSON object received as a string correctly?

开发者 https://www.devze.com 2023-01-16 03:30 出处:网络
I\'ve got a broken web开发者_如何学Python service that I can\'t access and alter. It sends down some mainly nice JSON, but one of the attributes is a nested JSON object that is being sent down as a st

I've got a broken web开发者_如何学Python service that I can't access and alter. It sends down some mainly nice JSON, but one of the attributes is a nested JSON object that is being sent down as a string.

http://www.ireland.com/api/getitemweb/185213

CustomJsonData in the response from the above url is the example.

My question is how could I interpret the CustomJsonData string as an object?

I thought the 'evil' eval() might do it, but no luck.

Thanks, Denis


If you are using eval, you need to add a ( and ) to the string before eval:

var parsedObject = eval("(" + jsonString + ")");

However, as you said, eval is evil, using parseJson from jquery is better (and extra parens not required):

var parsedObject = Jquery.parseJSON(jsonString);

Documentation for jQuery parseJSON: http://api.jquery.com/jQuery.parseJSON/


Use Douglas Crockford's implementation: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Example:

var obj = JSON.parse(aJsonString);

It handles nested arrays, objects, etc.


You have to parse the data twice -- once to parse the entire API JSON string and once to parse the custom JSON string.

function parseJSON(data) {
    return JSON ? JSON.parse(data) : eval('(' + data + ')');
}

var data = parseJSON(apiStr);
var custom = parseJSON(data.CustomJsonData);
0

精彩评论

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

关注公众号