Node.js JSON parsing
Problem
I have a JSON string that looks like this:
{
"resultType" : "history",
"currentTime" : "2011-10-22T15:46:00+00:00",
"columns" : ["date","orders","quantity","low","high","average"],
"rowsets" : [
{
"generatedAt" : "2011-10-22T15:42:00+00:00",
"rows" : [
["2011-12-03T00:00:00+00:00",40,40,1999,499999.99,35223.50],
["2011-12-02T00:00:00+00:00",83,252,9999,11550,11550]
]
}
]
}
Every time I try to parse it, I use code like this:
var data = JSON.parse(json);
console.log(data);
And the following is what is printed to the console:
{
"resultType" : "history",
"currentTime" : "2011-10-22T15:46:00+00:00",
"columns" : ["date","orders","quantity","low","high","average"],
"rowsets" : [
{
"generatedAt" : "2011-10-22T15:42:00+00:00",
"rows" : [Object]
}
]
}
I've tried a couple of things, but how can I get the data in the rows
field? After parsing, the console just shows [Object]
.
Solution
The output you're seeing is just the way it's being displayed. If you access data.rowsets[0].rows
, you can see that the JSON was indeed successfully parsed. You can also use util.inspect()
when specifying the depth
property to tell Node.js to recurse deeper when formatting the object.
Here is an example using util.inspect()
:
var data = JSON.parse(json);
// a null depth means to recurse indefinitely
console.log(util.inspect(data, { depth: null }));
Discussion
View additional discussion.