当我使用JSON.parse并使用require
模块注销一些获取的数据时,嵌套对象被记录在[Object]
中。下面是一个示例(当前使用的是Node版本10.15):
const request = require("request");
const url = "https://www.reddit.com/r/javascript.json";
request(url, (error, response) => {
const data = JSON.parse(response.body);
console.log(data)
});
{ kind: 'Listing',
data:
{ modhash: '',
dist: 26,
children:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ],
after: 't3_bf4cl6',
before: null } }
我在看这个问题:JSON.parse returns [object] from JSON
问这个问题的人很好奇为什么在JSON.parse之后,对象会被记录为[Object]
。最上面的答案指出,JSON.parse隐藏数据的原因是为了提高可读性。但是答案并没有解释覆盖默认行为的方法。
如何让JSON.parse记录完整的数据?有没有办法覆盖默认行为?
发布于 2019-04-20 21:51:57
如果直接记录response.body
没有按照您喜欢的方式进行格式化,这就是为什么您要执行JSON.parse
,那么要记录完整格式化的对象,请执行console.log(JSON.stringify(JSON.parse(response.body), null, 2))
发布于 2019-04-20 22:06:29
这不是JSON.parse,而是console.log对嵌套对象的默认行为。可以使用node的util.inspect
进行深度日志记录
const {inspect} = require('util');
console.log(inspect(obj, false, null, true));
或者作为一个函数
function log(...data) {
data.forEach(d => console.log(inspect(d, false, null, true)));
}
https://stackoverflow.com/questions/55777363
复制相似问题