Home > Uncategorized > Comments in JSON?

Comments in JSON?

September 16th, 2008

Some of my students have discovered that JSON doesn’t support comments — they’re not in the syntax diagram on the json.org home page or the RFC, and various discussion threads bemoan their absence.  We’d like to use JSON both for data interchange and for specifying test fixtures; we could live without comments for the former if we had to, but it’s a real pain to (for example) have the encrypted version of a password in a test fixture, but not the plaintext password it was derived from.  One possibility is to add a “comment” field to every data type that needs commenting (e.g., the dictionary that represents a User object would have “comment” as one of its keys), but then the mapping from JSON to object or database entry is no longer 1-1.  How are other people dealing with this?

Uncategorized

  1. September 16th, 2008 at 10:06 | #1

    Use YAML for the fixtures? JSON is a subset of YAML, so it shouldn’t be too much hassle.

  2. Dave Doyle
    September 16th, 2008 at 10:28 | #2

    Why store the test fixture in JSON? Store it in YAML (similar although much bigger syntax that allows comments) and turn it into JSON if/when needed.

  3. Koen
    September 16th, 2008 at 14:03 | #3

    The original specification (a few years ago) of JSON had comments included in the definition. However, it was removed, with the argument that JSON is meant as a machine interchange format only… or something like that.

  4. September 20th, 2008 at 02:35 | #4

    a search turns up some wrong answers by people who think you can just use javascript comments, because they don’t realize JSON is more than just passing a string to eval().

    You can hack comments by taking advantage of the looseness of parsers in basically taking the last value for any key in a hash. This means you can do stuff like this:

    {“name”: “// The name of something”,
    “name”: “foo”}

    It is not pretty, but it works.

    That being said, who the heck needs comments in JSON?

  5. September 20th, 2008 at 13:13 | #5

    @Calvin: we’re using JSON to describe test fixtures, and want comments (a) just because, and (b) so that when we’ve got an encrypted password stored as ASCII in a user record, we can also include the unencrypted password.

  6. November 17th, 2009 at 14:06 | #6

    Out of curiosity — why would you store the unencrypted password? You should simply rehash the password the user is trying to log in as and then compare the hashes. Storing unencrypted passwords is evil. But a) is still a good reason.
    Anyway, one easy way:
    {“some_dictionary”: “field”, “_comment”: “this is a comment”}
    But, as Calvin rightfully pointed out, you cannot legally use Javascript comments inside of JSON. JSON is a subset of Javascript, and comments are one of the things that’s outside the set.

Comments are closed.