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?
The easiest way is calling eval()
function.
var obj = eval('[' + jsonString + ']');
But you can also find mini libraries that can do JSON manipulation.
You could use jQuery and do the web service call via getJSON
Or you could use the official json parser.
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
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.