如何在Node JS中打印对象 [英] How to print object in Node JS

查看:506
本文介绍了如何在Node JS中打印对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码(在Node JS上运行)中,我尝试使用JSON.stringify打印从外部API获取的对象,这将导致错误:

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:

TypeError:将圆形结构转换为JSON

TypeError: Converting circular structure to JSON

我已经查看了有关此主题的问题,但没有一个可以帮上忙.有人可以建议:

I have looked at the questions on this topic, but none could help. Could some one please suggest:

a)如何从res对象获得country值?

a) How I could obtain country value from the res object ?

b)我如何打印整个对象本身?

b) How I could print the entire object itself ?

  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}`);
  });

推荐答案

通过使用http request客户端,我能够打印JSON对象以及打印country值.下面是我的更新代码.

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.

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
  }
});

这篇关于如何在Node JS中打印对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆