我写了一个快速脚本来解析两个相当大的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功能。我不知道我在那里做错了什么。我想弄明白,因为我想扩大这个范围,所以我可以选择性地打印。
确实'的console.log(recs.length);'输出一个非零的数? – Razor
是的,它输出17005. – RockyMountainHigh
连接一个'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)并呈现为更有用的格式。 –