1

Is there a function to un-JSON a String? I guessing it wouldn't be built in to JQuery, but could it be pulled off by writing a script that manipulates the String? I'm encountering this in the following.

I'm using the NYTimes API, but it doesn't support JSONP, so I'm trying to find alternatives to access it. I can't use a server-side proxy by virtue of the circumstances this script will be run in. I am trying YQL here, but the text returned is really messy. It is the JSON text as a String, and I can't use the JSON parsing capability. In other words, the text returned by YQL is the JSON of the JSON.

See this question for more context.

Community
  • 1
  • 1
Abbey Graebner
  • 1,837
  • 2
  • 11
  • 8
  • 1
    `result` is JSON. You can parse it using `JSON.parse`: `var obj = JSON.parse(result);`. Then `obj.query.results.p` contains JSON again. You can parse it with `JSON.parse`: `var p = JSON.parse(obj.query.results.p);` and so on... if you have a string and it contains JSON, use `JSON.parse`. Always. If `JSON.parse` is not available, then include this library: https://github.com/douglascrockford/JSON-js – Felix Kling Mar 01 '12 at 21:58
  • That's not working. See [Jsfiddle](http://jsfiddle.net/3NdEY/6/). It just returns `[object Object]`. – Abbey Graebner Mar 01 '12 at 22:00
  • 2
    Yes, that's the default string representation of an object (which means it **does** work). What do you expect an object to look like? A better debugging method is `console.log`: http://jsfiddle.net/3NdEY/7/ (use Chrome, open the console). You are meant to access the properties of the object. Example: http://jsfiddle.net/3NdEY/8/ – Felix Kling Mar 01 '12 at 22:02
  • Can you write down an example of how the fake JSON looks like? – hugomg Mar 01 '12 at 22:03
  • @ Felix Cool, thanks a lot! I'm kind of a JS novice. – Abbey Graebner Mar 01 '12 at 22:06

3 Answers3

2

try using JSON.parse() method

DrStrangeLove
  • 11,227
  • 16
  • 59
  • 72
  • I replied that, then deleted it because I read OP had written "I can't use the JSON parsing capability"... although I don't really understand why – Jim Blackler Mar 01 '12 at 21:56
2

If you don't want JSON.parse, but you're looking for a jquery way, then you can use

$.parseJSON(jsonString);
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
0

try

var myObject = eval('(' + myJSONtext + ')');
user1027167
  • 4,320
  • 6
  • 33
  • 40
  • This is the naive way, which is quite insecure. Consider `myJSONtext` to be altered by someone evil so that it is equal to `"alert('hacked')"`. – pimvdb Mar 01 '12 at 22:12