2014-04-03 63 views
0

我寫了一個快速腳本來解析兩個相當大的json文件(〜17k記錄)來比較兩者。我已經證實他們都是有效的json(通過jsonlintpro)和相同的格式。 (源代碼是相同的,所以這應該是給定的,但是,我總是認爲這個錯誤是我的,而我仍然會這樣做,只是在其他地方。)但是,解析後的文件只輸出[object,Object]。我想知道原因可能是什麼?解析json與node.js的問題

JSON格式是這樣的小片段(匿名當然):

[ 
{ 
    "id": "1234", 
    "name": "Name1", 
    "url": "https://localhost/Name1", 
    "date_created": "2013-07-05T18:47:05Z", 
    "date_cancelled": "", 
    "props": [ 
     { 
      "id": "54321", 
      "type": "Client", 
      "value": "General Store" 
     }, 
     { 
      "id": "65432", 
      "type": "Contact_Name", 
      "value": "Joe Smith" 
     } 
    ] 
}, 
{ 
    "id": "23456", 
    "name": "Name2", 
    "url": "https://localhost/Name2", 
    "date_created": "2014-02-27T17:46:43Z", 
    "date_cancelled": "", 
    "props": [ 
     { 
      "id": "34567", 
      "type": "Client", 
      "value": "Bait Shop" 
     } 
    ] 
}] 

這裏是相關代碼:

var _ = require('underscore'); 
var recs = require('./prod.json'); 

printArr(recs); 

console.log(recs.length); 

function printArr(arr) { 
     arr.forEach(function(item) { 
       console.log(item + ", "); 
     }); 
} 

任何指導,將不勝感激。

UPDATE:

好了,顯然這個問題是我printArr功能。我不知道我在那裏做錯了什麼。我想弄明白,因爲我想擴大這個範圍,所以我可以選擇性地打印。

+0

確實'的console.log(recs.length);'輸出一個非零的數? – Razor

+0

是的,它輸出17005. – RockyMountainHigh

+1

連接一個'Object'強制它成爲一個'String',這將導致''[[object Object]「](http://ecma-international.org/ecma-262/ 5.1 /#仲丁基15.2.4.2)。通過傳遞每個'Object'作爲自己的參數,'console.log(item)',它們將被[檢查](http://nodejs.org/api/util.html#util_util_inspect_object_options)並呈現爲更有用的格式。 –

回答

3

解析後的文件只輸出[object,Object]。

這是預期的行爲,因爲你是連接一個對象與一個字符串。

嘗試console.log(item)代替

0

console.log(item);確實應該打印[object, Object],你有沒有嘗試輸出它的屬性呢?

function printArr(arr) { 
    arr.forEach(function(item) { 
     console.log(item.id, item.name, item.url, item.date_created, item.date_cancelled, item.props, ';'); 
    }); 
} 
0

只需從prod.json文件導出值即可。

prod.json文件

module.exports = [ 
{ 
    "id": "1234", 
    "name": "Name1" 
}, 

{ 
    "id": "1234", 
    "name": "Name1" 

}] 

別處

var recs = require('./prod.json') 
console.log(recs)