jsonpath icon indicating copy to clipboard operation
jsonpath copied to clipboard

Detect circular references and return early

Open iamvery opened this issue 8 years ago • 3 comments

I ran into this issue today while dealing with a large object tree that contained circular references. Due to the recursive nature of the path I was using, the result was a RangeError: Maximum call stack size exceeded. For my particular use case, it would be preferable for jsonpath to be resilient to such cases by avoiding traversing circular references again.

My solution is keep a set of visited objects as the tree is traversed. If the same object shows up twice then descend avoids visiting it again.

Hope you find this useful! Let me know if somethings needs more work ❤️

iamvery avatar Aug 17 '17 00:08 iamvery

It looks like the version of Node used in CI doesn't support Set, so I just pushed a commit that uses a (slower) Array implementation. Not sure if upgrading Node is an option. Let me know!

iamvery avatar Aug 17 '17 00:08 iamvery

It looks like this handles references in objects. What happens if the circular reference occurs within an array?

var containsItself = ['value'];
containsItself.push(containsItself);
var results = jp.query(obj, '$..*');

jeremy-w avatar Aug 17 '17 01:08 jeremy-w

Nice catch!

Unfortunately there seems to be some other more subtle issue as well. I have yet to reproduce it in this lib's test suite, but in my application code the terminal completely hangs when traversing the problematic object. Interestingly, when I remove the "fix" I added to account for non-circular repetition then things run fine... Where's the loop??? 🤔

iamvery avatar Aug 17 '17 02:08 iamvery