Skip to content
Advertisement

How to parse json file with c-style comments?

I have a json file, such as the following:

    { 
       "author":"John",
       "desc": "If it is important to decode all valid JSON correctly  
and  speed isn't as important, you can use the built-in json module,   
 orsimplejson.  They are basically the same but sometimes simplej 
further along than the version of it that is included with 
distribution."
       //"birthday": "nothing" //I comment this line
    }

This file is auto created by another program. How do I parse it with Python?

Advertisement

Answer

I can not imagine a json file “auto created by other program” would contain comments inside. Because json spec defines no comment at all, and that is by design, so no json library would output a json file with comment.

Those comments are usually added later, by a human. No exception in this case. The OP mentioned that in his post: //"birthday": "nothing" //I comment this line.

So the real question should be, how do I properly comment some content in a json file, yet maintaining its compliance with spec and hence its compatibility with other json libraries?

And the answer is, rename your field to another name. Example:

{
    "foo": "content for foo",
    "bar": "content for bar"
}

can be changed into:

{
    "foo": "content for foo",
    "this_is_bar_but_been_commented_out": "content for bar"
}

This will work just fine most of the time because the consumer will very likely ignore unexpected fields (but not always, it depends on your json file consumer’s implementation. So YMMV.)

UPDATE: Apparently some reader was unhappy because this answer does not give the “solution” they expect. Well, in fact, I did give a working solution, by implicitly linking to the JSON designer’s quote:

Douglas Crockford Public Apr 30, 2012 Comments in JSON

I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn’t.

Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.

So, yeah, go ahead to use JSMin. Just keep in mind that when you are heading towards “using comments in JSON”, that is a conceptually uncharted territory. There is no guarantee that whatever tools you choose would handle: inline [1,2,3,/* a comment */ 10], Python style [1, 2, 3] # a comment (which is a comment in Python but not in Javascript), INI style [1, 2, 3] ; a comment, …, you get the idea.

I would still suggest to NOT adding noncompliant comments in JSON in the first place.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement