在下面的代码(在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}`);
});
通过使用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
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句