user637980
user637980

Reputation: 73

Node.js JSON parsing

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].

Upvotes: 0

Views: 5892

Answers (2)

hexacyanide
hexacyanide

Reputation: 91799

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 }));

Upvotes: 9

Kamrul
Kamrul

Reputation: 7311

Have tested your code. It's fine.

   var a = {
      "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]
          ]
        }
      ]
    }

    var util = require('util');

    console.log(util.inspect(a.rowsets[0].rows, { showHidden: true, depth: null }));

Upvotes: 0

Related Questions