2013-09-24 93 views
0

我有一個JSON字符串,看起來像這樣:Node.js的JSON解析

{ 
    "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 data = JSON.parse(json); 
console.log(data); 

而下面什麼是打印到控制檯:

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

我已經試過幾件事情,但我怎樣才能在rows字段中的數據?解析後,控制檯只顯示[Object]

回答

9

您看到的輸出只是它顯示的方式。如果您訪問data.rowsets[0].rows,則可以看到JSON確實已成功解析。在指定depth屬性時,您還可以使用util.inspect()來指示Node.js在格式化對象時遞歸更深。

下面是使用util.inspect()一個例子:

var data = JSON.parse(json); 
// a null depth means to recurse indefinitely 
console.log(util.inspect(data, { depth: null })); 
+0

您可以使用'data.rowsets [0] .rows'來訪問它。 'rowsets'是一個數組。 – Rowno

+0

這與陣列括號完成了這個訣竅。謝謝! – user637980

0

已測試你的代碼。沒關係。

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