0

Passing an object to JSON.stringify throws the error "Converting circular structure to JSON" but I'm not exactly sure why.

I'm passing the object via server-side node.js

app.get('/', function(req,res){
    res.render('index.jade', {object: object});
});

to Jade

script var table = !{JSON.stringify(object)};

And it's throwing the error when Jade tries to parse the object.

But I have no reason to believe object have circular references. Infact I do a

console.info(JSON.stringify(req.user.table.export))

right before res.render and it works fine!

Is there a way to know precisely where did the circular reference come into being?

edit found something, but unfortunately can't use it in Jade.

edit2 actually can

Community
  • 1
  • 1
laggingreflex
  • 32,948
  • 35
  • 141
  • 196

1 Answers1

0

In Jade

- var cache = [];
script var table = !{JSON.stringify(table,function(key, value) {if (typeof value === 'object' && value !== null) {if (cache.indexOf(value) !== -1) {console.log('Found Circular reference: '+key);return;}cache.push(value);}return value;})};
- cache = null;

output

{"players":[{"id":"53179fd401d540b8c5000001","username":...
Found Circular reference: table
connections property is deprecated. Use getConnections() m
Found Circular reference: owner
Found Circular reference:
Found Circular reference: sockets
Found Circular reference: store
Found Circular reference: manager
Found Circular reference: manager
Found Circular reference: mime
Found Circular reference: mime
Found Circular reference: mime
Found Circular reference: mime
Found Circular reference: user
Found Circular reference: user
Found Circular reference: _idleNext
Found Circular reference: _idlePrev
Found Circular reference: _idleNext
Found Circular reference: j1sYyxSoI8LEw5DNYGUa
Found Circular reference: manager
Found Circular reference: store
Found Circular reference: table

source

no idea why it's happening though... (link to issue on /Jade github)

Community
  • 1
  • 1
laggingreflex
  • 32,948
  • 35
  • 141
  • 196
  • If you want to restore the circular reference when parsing the JSON try [this](http://stackoverflow.com/a/23961876/2464634) – Preston S May 30 '14 at 19:39