2

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

Denis Hoctor
  • 2,597
  • 4
  • 33
  • 51

3 Answers3

6

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/

Robert Brown
  • 10,888
  • 7
  • 34
  • 40
David
  • 2,785
  • 1
  • 16
  • 8
  • 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 Sep 16 '10 at 01:37
  • Eval is not evil just like a drill does not kill just because it rhymes. Learn to use JS, it's a tool. – Michael J. Calkins Jul 19 '13 at 17:06
  • i did the same and then i past parsedObject as source to jquery autocomplete, did i do any wrong on that? –  Oct 07 '13 at 21:33
  • to Michael Calkins - eval is evil - says so in this article >D http://alistapart.com/article/better-javascript-minification basically, objection is that it doesn't allow auto minification to itself or containing context – binderbound Nov 24 '14 at 00:57
  • although eval for JSON evaluations should not cause issues if minifier is smart enough – binderbound Nov 24 '14 at 01:02
4

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.

Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
0

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 Chu
  • 25,069
  • 10
  • 40
  • 59
  • 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 Sep 16 '10 at 00:08