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?
-
Obligatory link: json.orguser166390– user16639001/21/2011 04:53:03Commented Jan 21, 2011 at 4:53
-
"JSON Object" is kind of an oxymoron. It's either an object, or a JSON string. Both not both at the same time.Ateş Göral– Ateş Göral01/21/2011 05:11:01Commented Jan 21, 2011 at 5:11
4 Answers
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.
-
+1 because ... 1) Someone else has already solved this problem 2) Someone else has already solved this problem in a good way.user166390– user16639001/21/2011 04:55:49Commented Jan 21, 2011 at 4:55
-
Except that jQuery.parseJSON() doesn't serialize .Net DateTime objects into jscript date objects. Instead they're simply deserialized to strings.Jeff LaFay– Jeff LaFay09/13/2012 15:26:16Commented Sep 13, 2012 at 15:26
-
@jlafay JSON (as per the JSON specification) doesn't support
Date
objects. SincejQuery.parseJSON
will parse a validJSON
string into a JavaScript object, I would not expect it to deserializeDate
objects at all regardless of their format.Zack The Human– Zack The Human10/28/2012 00:34:29Commented Oct 28, 2012 at 0:34
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.
-
@pst What? The alternative is there -- and if you use that alternative you get Date handling thrown in.Jeffrey Hantin– Jeffrey Hantin01/21/2011 05:16:21Commented Jan 21, 2011 at 5:16
Pretty standard, not so safe:
eval('(' + json + ')');
Kind of cool thing that jQuery does, still not very safe:
(new Function('return ' + json))();
-
@pst Using
window.JSON.parse
and never working with IE 6 or 7.sdleihssirhc– sdleihssirhc01/21/2011 04:59:18Commented Jan 21, 2011 at 4:59