Given a string of JSON data, how can you safely turn that string into a JavaScript object?
Obviously you can do this unsafely with something like...
var obj = eval("(" + json + ')');
...but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.
If you're using jQuery, you can also just do
$.getJSON(url, function(data) { });
Then you can do things like
data.key1.something
,data.key1.something_else
, etc.The easiest way using
parse()
method:then you can get the values of the
Json
elements, for example:Using jQuery as described in the documentation:
This seems to be the issue:
An input is received, via ajax websocket etc, and it is always gonna be in String format - but you need to know if it is JSON.parsable. Touble is, that if you always run it through a JSON.parse, the program MAY continue 'successfully' but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'".
Converting the object to JSON, and then parsing it, works for me, like:
Summary:
Javascript (both browser and NodeJS) have a built in
JSON
object. On this Object are 2 convenient methods for dealing withJSON
. They are the following:JSON.parse()
TakesJSON
as argument, returns JS objectJSON.stringify()
Takes JS object as argument returnsJSON
objectOther applications:
Besides for very conveniently dealing with
JSON
they have can be used for other means. The combination of bothJSON
methods allows us to make very easy make deep clones of arrays or objects. For example:The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the
$.parseJSON()
method.