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 ?
JavaScript
x
10
10
1
http.get('http://ip-api.com/json', (res) => {
2
console.log(`Got response: ${res.statusCode}`);
3
console.log(res.country) // *** Results in Undefined
4
console.log(JSON.stringify(res)); // *** Resulting in a TypeError: Converting circular structure to JSON
5
6
res.resume();
7
}).on('error', (e) => {
8
console.log(`Got error: ${e.message}`);
9
});
10
Advertisement
Answer
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.
JavaScript
1
9
1
var request = require('request');
2
request('http://ip-api.com/json', function (error, response, body) {
3
if (!error && response.statusCode == 200) {
4
console.log(response.body); // Prints the JSON object
5
var object = JSON.parse(body);
6
console.log(object['country']) // Prints the country value from the JSON object
7
}
8
});
9