Skip to content Skip to sidebar Skip to footer

How Can I Interpret A Json Object Received As A String Correctly?

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 str

Solution 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/

Solution 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.

Solution 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 + ')');
}

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

Post a Comment for "How Can I Interpret A Json Object Received As A String Correctly?"