views:

36

answers:

3

Hi,

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

+2  A: 

Use Douglas Crockford's implementation: http://www.json.org/json2.js

Example:

var obj = JSON.parse(aJsonString);

It handles nested arrays, objects, etc.

SimpleCoder
A: 

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/

David
This is the option for me now as I'm hoping the service will be fixed in the coming days. If it's not I'll clean it up and use SimpleCoders suggestion as jQuery isn't an option for me in this app either. Thanks guys.
Denis Hoctor
A: 

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);
Casey Hope
Note that due to a dodgy bit of design, it's valid to put the obscure Unicode line ending characters U+2028 and U+2029 in a JSON string literal, but they're not valid in a JavaScript string literal. Therefore for safety you should replace `'\u2028'` with `'\\u2028'` and the same for U+2029, before wrapping in brackets and `eval`ing.
bobince