muba has asked for the wisdom of the Perl Monks concerning the following question:

Preliminary tl;dr: are circular references normally allowed in JSON? And if so, how is it, algorithmically, handled on both ends of a typical browser + AJAX + serverside setup?

A little background

Out of curiosity to see if I could do it, and also because I'm not overly happy with the interface of the standard(?) JSON modules out there, I decided to roll my own Perl-to-JSON module (and plan to include a JSON-to-Perl part too, but that's another issue).

Halfway through getting something working surprisingly well, I wondered if it would work if I threw something with a circular reference at it. It did what I expected and hurled itself into an endless loop. Not good, so for the time being I slapped a maximum depth onto it.

That's only a half-assed solution, of course, so I put myself to some research - how does JSON normally "handle" circular references? It didn't take me long to stumble upon the RFC and it doesn't make mention of any such thing.

In conclusion

So, in conclusion, my questions:

  • Comment on (OT) JSON - circular references allowed or not?

Replies are listed 'Best First'.
Re: (OT) JSON - circular references allowed or not?
by moritz (Cardinal) on Sep 12, 2011 at 15:40 UTC

    JSON serializes a tree, so no circular data structures out of the box.

    Of course you can still establish circular data structures by convention and post-processing (for example give each objecht an __id__, and allow references like __ref__:$object_id).

    One attempt to specify such a system is jsync, which uses the ideas from YAML, but stays with a JSON syntax.

    (Note that JSON is not a serialization format, but rather a data exchange language, and thus is limited to a feature set available in nearly all programming languages).

      I had never thought of the distinction between serialization and a data exchange format, thanks for pointing that out. That's a most satisfying answer. If circular references aren't part of standard JSON I'm not going to bother with implementing support for it.

      On a sidenote I'm proud to report that the JSON-to-Perl part is also almost working. It has a few quirks I'm not too happy about but they should be resolved easily.

Re: (OT) JSON - circular references allowed or not?
by Anonymous Monk on Sep 12, 2011 at 15:11 UTC

    I don't think it does

    JSON, like all nameless data structures, cannot be self-referential

    Ex

    my $a ; $a = [ \$a ] ; # self referential, but
    If it wasn't for name $a, then $a couldn't refer to itself
    [ # used to be $a [] # WHOOPS, not $a ]

    JSON is JavaScript without named variables

    I suppose there might be js libraries that try to overcome this limitation by doing the mapping for you, but i've not seen one