简体   繁体   中英

How to convert JSON string to JSON Object using JavaScript?

I use the JavaScriptSerializer class of ASP.net to serialize my object and return it to the client side. How can I deserialize the string using JavaScript?

If you're using jQuery already, you'll be happy to know that you can parse a JSON string with jQuery.parseJSON .

If you aren't using jQuery and don't want to, you can always use the wonderful JSON.parse or json_parse , written by none other than Douglas Crockford himself.

I would avoid eval() if it isn't necessary.

I am going to propose ... do nothing . This assumes the serialized result is returned with the page and/or an additional HTML fragment.

// In some JavaScript area somewhere in the ASP page
var myObject = <%= JSONIfiedObjectResult %>;

This works and is valid because JSON is a subset of JavaScript literals . Note that I did not put quotes around the <%= %> .

If the de-serialization is the result on an AJAX call returning JSON, etc, then see Zack's answer.

Pretty trivial -- just do

var x = eval(theString);

which should get everything except ASP.Net's unique serialization of DateTime , which is not supported by "real" JSON and is an ASP.Net extension. To use ASP.Net's deserializer, make sure you include an <asp:ScriptManager> tag in your page, and call

var x = Sys.Serialization.JavaScriptSerializer.deserialize(theString);

which will invoke the special Date handling and probably get you better security.

Pretty standard, not so safe:

eval('(' + json + ')');

Kind of cool thing that jQuery does, still not very safe:

(new Function('return ' + json))();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM