Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  134] [ 3]  / answers: 1 / hits: 105665  / 8 Years ago, thu, august 4, 2016, 12:00:00

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: Converting circular structure to 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 ?



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

More From » json

 Answers
18

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

[#61146] Tuesday, August 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anthonyw

Total Points: 589
Total Questions: 117
Total Answers: 117

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;