Reputation: 557
I am trying to find a way to parse a JSON string which contains Date object.
> var obj = {}
> obj.date = new Date();
Mon Mar 19 2012 15:14:22 GMT-0700 (PDT)
> obj.number = 1
1
> obj.float = 1.1
1.1
> obj.str = "hello"
"hello"
> obj
Object
date: Mon Mar 19 2012 15:14:22 GMT-0700 (PDT)
float: 1.1
number: 1
str: "hello"
> YAHOO.lang.JSON.stringify(obj)
"{"date":"\"2012-03-19T22:14:22Z\"","number":1,"float":1.1,"str":"hello"}"
> parsed = YAHOO.lang.JSON.parse(str)
Object
date: ""2012-03-19T22:14:22Z""
float: 1.1
number: 1
str: "hello"
see that parsed.date is string where obj.date was previously Date object. What is the best way to parse JSON with nested objects?
thank you
Upvotes: 0
Views: 1330
Reputation: 39678
Use yui stringToDate function stringToDate turns strings in the iso8601 UTC format into Dates :
var parsed = YAHOO.lang.Json.stringToDate(str);
parsed.date will now contain a Date object and other element will be de_serialized too.
see an example here.
Upvotes: 0
Reputation: 349222
JSON cannot be used to de-serialize objects (Date
> String > ).Date
Only strings, numbers, object (literals), arrays, booleans and null can be serialiszed well.
You have to write a custom parser, which deals with the Date
object as follows:
Parse: Parse the timestamp using the Date
constructor. eg new Date(timestamp);
.
function parse(str) {
var obj = YAHOO.lang.JSON.parse(str);
obj.date = new Date(obj);
}
Upvotes: 2