问题
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