Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to put a Javascript Date in JSON data format?

Status
Not open for further replies.

davidchardonnet

Programmer
Mar 21, 2001
167
FR
Hello,

I want to convert to JSON some data i have defined in javascript like this:


var datasets =
{
"A":
{
label: "A",
data: [[new Date("2010/10/01"), 65.00],[new Date("2010/11/20"), 65.00]]
},
"B":
{
label: "B",
data: [[new Date("2010/10/01"), 57.00],[new Date("2010/11/20"), 57.00]]
},

"C": {
label: "C",
data: [[new Date("2010/10/01"), 65.00], [new Date("2010/10/12"), 64.00], [new Date("2010/10/16"), 62.50], [new Date("2010/10/24"), 61.00], [new Date("2010/11/01"), 61.50], [new Date("2010/11/09"), 78.40], [new Date("2010/11/10"), 60.00], [new Date("2010/11/18"), 57.00], [new Date("2010/11/19"), 62.00], [new Date("2010/11/20"), 75.00]] }
};


What i want to do is have this data in JSON format so i can recover the same information by a database request.

The problem is that i can't find the right way to have this data encoded to json so when i do an EVAL, the data is back in the "datasets" variable.

Can you help me?

Thank you

David
 
[0] You can use Andrea Giammarchi's JSON.js and use it's pure javascript encode and decode method of JSON object. It has special and valuable support of date datatype that you might need.

[1] With that include, you can test it simply by this.
[tt]
var s=JSON.encode(datasets);
alert(s);

var ds_derived=JSON.decode(s);
//for verification, spot checking
alert(ds_derived["A"]["label"]);
alert(ds_derived["B"]["data"]);
alert(ds_derived["B"]["data"][0][1]);
//etc ...[/tt]
 
Usually, databases accept dates as a string in something like this format: "yyyy-MM-dd hh:mm:ss". (Check the requirements on your specific db.)

To get the dates into that format, check out this library:


It is by far the best extension of the JavaScript Date Object that I've come across so far. Besides the formatting, it has some other cool features as well.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top