3

I am trying to send a JSON object back to my client using a websites API and am getting the following error.

var body = JSON.stringify(obj, replacer, spaces);

TypeError: Converting circular structure to JSON
at Object,stringify (native)

Here is my code

app.get('/api/test', function(req, res){
   http.get('http://api.biblia.com/v1/bible/content/LEB.txt.json?passage=John3.16&key=fd37d8f28e95d3be8cb4fbc37e15e18e', function(data) {
       res.json(data);
   });
});

If I replace data with a simple JSON object {"test":"test"}. Everything works fine. Any help with understanding what is even occuring would be helpful. I am using an Express.js Node.js Angular.js stack. Thank you!

Kyle Copeland
  • 479
  • 1
  • 3
  • 14
  • you should log the data you are getting back from the biblia api and make sure it's what you are expecting. – Brian Glaz Jan 30 '14 at 21:09

1 Answers1

0

The data variable in your callback is actually an instance of http.IncomingMessage, which is much more complex than just data. The error you're getting is because it has circular references, so you need to filter it out. There is an answer here that outlines this process using the code below:

var cache = [];
JSON.stringify(o, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Circular reference found, discard key
            return;
        }
        // Store value in our collection
        cache.push(value);
    }
    return value;
});
cache = null; // Enable garbage collection
Community
  • 1
  • 1
SamT
  • 10,374
  • 2
  • 31
  • 39