Javascript 如何在 Node JS 中打印对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38768567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print object in Node JS
提问by kurrodu
In the below code (running on Node JS) I am trying to print an object obtained from an external API using JSON.stringify
which results in an error:
在下面的代码(在 Node JS 上运行)中,我试图打印从外部 API 获取的对象,使用JSON.stringify
这会导致错误:
TypeError: Converting circular structure to JSON
类型错误:将圆形结构转换为 JSON
I have looked at the questions on this topic, but none could help. Could some one please suggest:
我已经查看了有关此主题的问题,但没有任何帮助。有人可以建议:
a) How I could obtain country
value from the res
object ?
a) 我如何country
从res
对象中获取价值?
b) How I could printthe entire object itself ?
b) 我如何打印整个对象本身?
http.get('http://ip-api.com/json', (res) => {
console.log(`Got response: ${res.statusCode}`);
console.log(res.country) // *** Results in Undefined
console.log(JSON.stringify(res)); // *** Resulting in a TypeError: Converting circular structure to JSON
res.resume();
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});
采纳答案by kurrodu
By using the http request
client, I am able to print the JSON object as well as print the country
value. Below is my updated code.
通过使用 httprequest
客户端,我可以打印 JSON 对象以及打印country
值。下面是我更新的代码。
var request = require('request');
request('http://ip-api.com/json', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.body); // Prints the JSON object
var object = JSON.parse(body);
console.log(object['country']) // Prints the country value from the JSON object
}
});
回答by DrakaSAN
Basic console.log
will not go through long and complex object, and may decide to just print [Object]
instead.
Basicconsole.log
不会经历冗长而复杂的对象,并且可能决定只打印[Object]
。
A good way to prevent that in node.js is to use util.inspect
:
在 node.js 中防止这种情况的一个好方法是使用util.inspect
:
'use strict';
const util = require('util'),
obj = /*Long and complex object*/;
console.log(util.inspect(obj, {depth: null}));
//depth: null tell util.inspect to open everything until it get to a circular reference, the result can be quite long however.
EDIT: In a pinch (in the REPL for example), a second option is JSON.stringify
. No need to require
it, but it will break on circular reference instead of printing the fact there is a reference.
编辑:在紧要关头(例如在 REPL 中),第二个选项是JSON.stringify
. 不需要require
它,但它会中断循环引用而不是打印存在引用的事实。
回答by Tomá? Zato - Reinstate Monica
Print the whole object, it will not have problems with recursive refferences:
打印整个对象,递归引用不会有问题:
console.log(res);
Here's an example for you to see how console.log handles circular refferences:
下面是一个示例,让您了解 console.log 如何处理循环引用:
> var q = {a:0, b:0}
> q.b = q
> console.log(q)
{ a: 0, b: [Circular] }
Also, I would advise to check what data are you actually receiving.
另外,我建议您检查一下您实际收到的数据。
回答by Sami
You do not actually get data in res
. You need on('data')
and on.('end')
您实际上并没有在res
. 你需要on('data')
和on.('end')
body
is a string. It gets append on data received, so on complete you will need to parse data into json
body
是一个字符串。它会附加收到的数据,因此完成后您需要将数据解析为 json
http.get("http://ip-api.com/json", function(res) {
var body = '';
res.on('data', function(data){
body = body + data;
});
res.on('end', function() {
var parsed = {};
try{
parsed = JSON.parse(body); // i have checked its working correctly
}
catch(er){
//do nothing it is already json
}
console.log(parsed.country);
});
});
Noe from parsed
which is a json object, you can get any property
Noe从中parsed
是一个json对象,你可以得到任何属性
回答by black hat
You can pass two arguments to console.log()
您可以将两个参数传递给 console.log()
Try this code after installing "yargs" And it will print whole object
安装“yargs”后试试这个代码它会打印整个对象
console.log('object is' , yargs.argv);
console.log('object is' , yargs.argv);
I think may be it will help you to print whole object :)
我认为它可能会帮助您打印整个对象:)
回答by zemunkh
This can print the key of the object and the value of the object in the simplest way. Just try it.
这可以以最简单的方式打印对象的键和对象的值。就试一试吧。
const jsonObj = {
a: 'somestring',
b: 42,
c: false
};
Array.from(Object.keys(jsonObj)).forEach(function(key){
console.log(key + ":" + jsonObj[key]);
});