kur*_*odu 5 javascript json node.js
在下面的代码中(在Node JS上运行)我试图打印从外部API获取的对象,JSON.stringify这会导致错误:
TypeError:将循环结构转换为JSON
我已经看过关于这个主题的问题,但没有人能提供帮助.有人可以建议:
a)我如何country从res物体中获得价值?
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}`);
});
Run Code Online (Sandbox Code Playgroud)
Dra*_*SAN 17
Basic console.log不会经历漫长而复杂的对象,可能会决定只打印[Object].
在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.
Run Code Online (Sandbox Code Playgroud)
通过使用 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
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35870 次 |
| 最近记录: |