views:

274

answers:

4

In my JavaScript I want to access the properties of a JSON serialzied object that was produced via a .NET web service. How do I deserialize the JSON data into an object that I can maniuplate in the JavaScript?

+1  A: 

The easiest way is calling eval() function.

var obj = eval('[' + jsonString + ']');

But you can also find mini libraries that can do JSON manipulation.

Robert Koritnik
I'm assuming something along the lines of:var deserializedObject = eval(jsonData); //correct?
Achilles
correct. Added some code afterwards that resembles yours :)
Robert Koritnik
A: 

You could use jQuery and do the web service call via getJSON

Or you could use the official json parser.

Mike Blandford
I'm using Dojo currently. Would you know of an equivalent function in Dojo's library?
Achilles
looks like there's a dojo.fromJson function that'll do it.
Mike Blandford
A: 

Try Dojo.json package. It contains toJson() and fromJson() functions.

You shouldn't use eval() unless you really trust your data provider. eval() can evaluate functions and call them, can raise random exceptions etc. Use libraries and you'll be on the safer side.

EDIT::

crescentfresh pointed out that dojo.fromJson() is just a wrapper for eval(). That's true, sadly, but even at JSON.org they say that eval() can be a security issue, and they should know what they're talking about :)

You can use external JSON parser (see: code.google.com/p/json-sans-eval for example), or just use dojo.fromJson() and hope they'll improve it in next version

Abgan
Here is the entire implementation of `"dojo.fromJson"`: `function(s){return eval("(" + s + ")")}`. See for yourself: http://svn.dojotoolkit.org/src/tags/release-1.3.2/dojo/_base/json.js
Crescent Fresh
No reason to include yet another library to use 1 or 2 methods; just do like olliej says below and go to json.org and get json2.js.
ken
+3  A: 

Use json2.js from http://json.org -- it provides a JSON object on the global object that provides a parse function. It has the added advantage of being the basis for the ES3.1 specification of JSON, and will use a native implementation of JSON if possible. This means that you can parse a json serialised object with:

object = JSON.parse(string)

Because of the way it is implemented this means if you page is viewed in a browser that supports JSON (eg. Safari 4, Firefox 3.5, even IE8) you will get a fast and secure parser automatically.

olliej