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

廉价感情. 提交于 2019-12-10 23:57:45

问题


I've got a broken web 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


回答1:


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/




回答2:


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.




回答3:


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);


来源:https://stackoverflow.com/questions/3722715/how-can-i-interpret-a-json-object-received-as-a-string-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!