Can I comment a JSON file?
2
Can I comment a JSON file? If so, how?
improve this question | comment
Ena Bins DVM Created at: 2013-11-13 17:07:07 UTC By Ena Bins DVM
@StingyJack:  To explain things that may not be obvious, or whatever else one might do with comments.  I for one often have comments in data files.  XML, ini files, and many other formats include provisions for comments. - Alek Larson
@StingyJack -- I have a key algorithm for my product that must be implemented in three separate languages: Javascript, Objective-C, and Python. A lot of this algorithm can be abstracted away into configuration. And what configuration syntax turns out to be easiest for me to consume in all three cases? JSON, of course. But I'd love to be able to document and comment directly in the configuration files. I realize JSON was originally intended strictly for interchange... but like all things, its use cases grow... - Camren Bednar
Note that where your JSON ends up going is a big part of whether you can or can't comment it. If it's for configuration, then it's likely that you have control over all the parsers that will read it. Since a JSON parser is an extremely simple creature, extending one to allow comments should be very simple.  Alternatively, you could use a YAML parser, and YAML does allow comments.  (In some ways YAML is a lot more flexible for configuration purposes anyway.) - Katharina Becker
If you, like me, were wondering whether //comments are OK for the specific use-case of a Sublime Text configuration file, the answer is yes (as of version 2). Sublime Text will not complain about it, at least, whereas it will complain about {"__comment": ...} in the console, because it is an unexpected field. - Alan Kilback
Y U NO allow comments - Mr. Ryann Dietrich
19 Answers
0
What I do to cut a Json into parts is adding "dummy comment" lines :

{

"#############################" : "Part1",

"data1"             : "value1",
"data2"             : "value2",

"#############################" : "Part2",

"data4"             : "value3",
"data3"             : "value4"

}

0
Sorry, We cant use comments in JSON... See the syntax diagram for JSON in JSON.org

Douglas Crockford says "why he removed comment in json and providing alternate way to do that"


  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.

0
I just released JSON.minify() which strips out comments and whitespace from a block of JSON and makes it valid JSON that can be parsed. So, you might use it like:  

  JSON.parse(JSON.minify(my_str));


When I released it, I got a huge backlash of people disagreeing with even the idea of it, so I decided that I'd write a comprehensive blog post on why comments make sense in JSON.  

Hopefully that's helpful to those who disagree with why JSON.minify() could be useful.
0
I've found a little hack that allows you to place comments in a JSON file that will not affect the parsing, or alter the data being represented in any way.

It appears that when declaring an object literal you can specify two values with the same key, and the last one takes precedence. Believe it or not, it turns out JSON parsers work the same way. So we can use this to create comments in the source JSON that will not be present in parsed object representation. 

({a: 1, a: 2});
// => Object {a: 2}
Object.keys(JSON.parse('{"a": 1, "a": 2}')).length; 
// => 1


If we apply this technique, your commented JSON file might look like this:

{
  "api_host" : "The hostname of your API server. You may also specify the port.",
  "api_host" : "hodorhodor.com",

  "retry_interval" : "The interval in seconds between retrying failed API calls",
  "retry_interval" : 10,

  "auth_token" : "The authentication token. It is available in your developer dashboard under 'Settings'",
  "auth_token" : "5ad0eb93697215bc0d48a7b69aa6fb8b",

  "favorite_numbers": "An array containing my all-time favorite numbers",
  "favorite_numbers": [19, 13, 53]
}


The above code is valid JSON. If you parse it you'll get an object like this:

{
    "api_host": "hodorhodor.com",
    "retry_interval": 10,
    "auth_token": "5ad0eb93697215bc0d48a7b69aa6fb8b",
    "favorite_numbers": [19,13,53]
}


Which means there is no trace of the comments, and they won't have weird side-effects.

Happy hacking!
0
Comments were removed from JSON by design.


  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.


Source: Public statement by Douglas Crockford on G+
0
You can't. At least that's my experience from quick glance to json.org

Json has its syntax visualized on that page. No note from comments.
0
Consider using YAML. It's nearly a superset of JSON (virtually all valid JSON is valid YAML) and it allows comments.
0
You should write a JSON schema instead. JSON schema is currently a proposed internet draft specification. Besides documentation, the schema can also be used for validating your json data.

Example:

 {
"description":"A person",
"type":"object",
"properties":
   {
    "name": 
        {
          "type":"string"
        },
    "age" : 
        {
          "type":"integer",
          "maximum":125
        }
   }
}


You can provide documentation by using the description schema attribute. 
0
If your text file, which is a JSON string, is going to be read by some program, how difficult would it be to strip out either c or c++ style comments before using it?  Answer: It would be a one liner.  If you do that then JSON files could be used as configuration files.
0
No, comments in JSON are not allowed. This answer is based on:

http://www.json.org
RFC 4627:
The application/json Media Type for JavaScript Object Notation (JSON)
0
JSON does not support comments natively, but you can make your own decoder or at least preprocessor to strip out comments, that's perfectly fine (as long as you just ignore comments and don't use them to guide how your application should process the JSON data).


  JSON does not have comments. A JSON encoder MUST NOT output comments.
  A JSON decoder MAY accept and ignore comments.
  
  Comments should never be used to transmit anything meaningful. That is
  what JSON is for.


Cf: Douglas Crockford, author of JSON spec.
0
Just encountering this for config files.  I don't want to use XML (verbose, graphically, ugly, hard to read), or "ini" format (no hierarchy no real standard etc) or java "Properties" format ( like .ini )  

JSON can do all they can do but way less verbose and more human readable - and parsers are easy and ubiquitous in many languanges.  It's just a tree of data.  But out of band comments are a necessity often to document "default" configurations and the like.  Configs are never to be "full documents" but trees of saved data that can be human readable when needed.

I guess one could use "#": "comment", for "valid" JSON
0
The Dojo javascript toolkit (at least as of version 1.4), allows you to include comments in your JSON. The comments can be of /* */ format. Dojo consumes the JSON via the dojo.xhrGet() call.

Other javascript toolkits may work similarly. If anybody finds one, please edit this response and include it.

This can be helpful when experimenting with alternate data structures (or even data lists) before choosing a final option.
0
Comments are not an official standard. Although some parsers support c-style comments. One that I use is JsonCpp. In the examples there is this one:

// Configuration options
{
    // Default encoding for text
    "encoding" : "UTF-8",

    // Plug-ins loaded at start-up
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],

    // Tab indent size
    "indent" : { "length" : 3, "use_space": true }
}


jsonlint does not validate this. So comments are a parser specific extension and not standard.
0
Depends on your json library, Json.net supports javascript style comments /* commment */.
See another SO question.
0
JSON makes a lot of sense for config files and other local usage because it's ubiquitous and because it's much simpler than XML. 

If people have strong reasons against having comments in JSON when communicating data (whether valid or not), then possibly JSON could be split into two:

JSON-COM: JSON on the wire, or rules that apply when communicating JSON data.
JSON-DOC: JSON document, or JSON in files or locally. Rules that define a valid JSON document.
JSON-DOC will allow comments, and other minor differences might exist such as handling whitespace. Parsers can easily convert from one spec to the other. 

With regards to the remark made by Douglas Crockford on this issues (referenced by @Artur Czajka)


  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.


We're talking about a generic config file issue (cross language/platform), and he's answering with a JS specific utility!

Sure a JSON specific minify can be implemented in any language,
but standardize this so it becomes ubiquitous across parsers in all languages and platforms so people stop wasting their time lacking the feature because they have good use-cases for it, looking the issue up in online forums, and getting people telling them it's a bad idea or suggesting it's easy to implement stripping comments out of text files.

The other issue is interoperability. Suppose you have a library or API or any kind of subsystem which has some config or data files associated with it. And this subsystem is
to be accessed from different languages.  Then do you go about telling people: by the way
don't forget to strip out the comments from the JSON files before passing them to the parser!
0
The idea behind JSON is to provide simple data exchange between applications. These are typically web based and the language is javascript. 

It doesn't really allow for comments as such, however, passing a comment as one of the name/value pairs in the data would certainly work, although that data would obviously need to be ignored or handled specifically by the parsing code.

All that said, it's not the intention that the JSON file should contain comments in the traditional sense. It should just be the data.

Have a look at the JSON website for more detail.
0
You can have comments in JSONP, but not in pure JSON. I've just spent an hour trying to make my program work with this example from Highcharts: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?

If you follow the link, you will see 

?(/* AAPL historical OHLC data from the Google Finance API */
[
/* May 2006 */
[1147651200000,67.79],
[1147737600000,64.98],
...
[1368057600000,456.77],
[1368144000000,452.97]
]);


Since I had a similar file in my local folder, there were no issues with the Same-origin policy, so I decided to use pure JSON... and, of course, $.getJSON was failing silently because of the comments. Eventually I just sent a manual HTTP request to the address above and realized that the content-type was text/javascript since, well, JSONP returns pure Javascript. In this case comments are allowed. But my application returned content-type application/json, so I had to remove the comments.
0
I don't believe you can have an actual comment.  The JSON should all be data, and if you include a comment, then it will be data too.

You could have a designated data element called "_comment" (or something) that would be ignored by apps that use the json data.

You would probably be better having the comment in the processes that generate/receive the json, as they are supposed to know what the json data will be in advance, or at least the structure of it. 

But if you decided to...

{
   "_comment" : "comment text goes here...",
   "glossary": {
      "title": "example glossary",
      "GlossDiv": {
         "title": "S",
         "GlossList": {
            "GlossEntry": {
               "ID": "SGML",
               "SortAs": "SGML",
               "GlossTerm": "Standard Generalized Markup Language",
               "Acronym": "SGML",
               "Abbrev": "ISO 8879:1986",
               "GlossDef": {
                  "para": "A meta-markup language, used to create markup languages such as DocBook.",
                  "GlossSeeAlso": ["GML", "XML"]
               },
               "GlossSee": "markup"
            }
         }
      }
   }
}

Your Answer