9580

Can I use comments inside a JSON file? If so, how?

22
  • 221
    @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. Commented Oct 28, 2008 at 20:51
  • 43
    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.
    – floer32
    Commented Feb 1, 2013 at 15:12
  • 39
    JSON5 supports comments: stackoverflow.com/a/7901053/108238
    – schoetbi
    Commented Feb 2, 2015 at 11:13
  • 26
    "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." - Douglas Crockford (Author of JSON), 2012 Commented Nov 20, 2019 at 15:45
  • 20
    Image the inventor of the hammer. He probably wanted to bust up rocks into flecks that could be used to make knives and axes. We'd still be in the stone age if he insisted that his tool could not be used for anything else, like hitting people attacking you, or turning wheat into flour, or driving nails. It's the height of hubris to assume that it's MY way or nothing. Neglecting comments is a great example of assuming this tool will never have another use than data communication between machines/programs. Such lack of foresight is shameful.
    – SMBiggs
    Commented Nov 20, 2020 at 20:44

62 Answers 62

7101

No.

JSON is data-only. If you include a comment, then it must be data too.

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

You would probably be better having the comment in the processes that generates/receives 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"
            }
         }
      }
   }
}
21
  • 311
    It might pay to have some kind of prefix on the actual comment in case there's ever a valid field named comment: "__comment":"comment text goes here...", Commented Feb 3, 2010 at 11:41
  • 40
    BTW, the json library for Java google-gson has support for comments.
    – centic
    Commented Oct 1, 2012 at 12:21
  • 19
    What about if I wanted a separate comment on the Accronym and Abbrev properties? I've used this pattern before but stopped since it doesn't allow me to do that. It is a hack. Maybe if I prepend a property name with __comment__ instead. That is "__comment__Abbrev", still a hack, but would let me comment on all prpoerties Commented Aug 11, 2014 at 12:58
  • 67
    you could also use "//": this looks more native and is still repeatable in the same parent
    – smnbbrv
    Commented Aug 28, 2015 at 9:59
  • 31
    When JSON is used for human-intended configuration files, they should be annotated for humans to understand better. Annotated, such file is no longer valid JSON, but there are solutions. For example, Google's GYP supports #-style comments. JSON.Minify will help you discard C/C++ style comments from your input file. Commented Feb 27, 2016 at 13:59
2169

No, comments of the form //… or /*…*/ are not allowed in JSON. This answer is based on:

  • https://www.json.org
  • RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON)
  • RFC 8259 The JavaScript Object Notation (JSON) Data Interchange Format (supercedes RFCs 4627, 7158, 7159)
11
  • 95
    If you'd like to annotate your JSON with comments (thus making it invalid JSON), then minify it before parsing or transmitting. Crockford himself acknowledged this in 2012 in the context of configuration files.
    – user23987
    Commented Aug 7, 2014 at 19:26
  • 40
    @alkuzad: When it comes to formal grammars, there must be something that explicitly says that they are allowed, not the other way around. For instance, take your programming language of choice: Just because some desired (but missing) feature isn't explicitly disallowed, doesn't mean that your compiler will magically recognize it. Commented Sep 28, 2015 at 7:01
  • 16
    Yes. The JSON format has a lot of dead-space between elements and is space-insensitive in those regions, so there's no reason why you can't have single or multi-line comments there. Many parsers and minifiers support JSON comments as well, so just make sure your parser supports them. JSON is used a lot for application data and configuration settings, so comments are necessary now. The "official spec" is a nice idea, but it's insufficient and obsolete, so too bad. Minify your JSON if you're concerned about payload size or performance.
    – Triynko
    Commented Oct 31, 2017 at 17:36
  • 123
    Although your answer is absolutely correct, it should be said that this is BS. With so many end users coming across the need for json configuration, then comments are exceedingly helpful. Just because some tin-foil hats decided that JSON is and must always be machine readable, ignoring the fact that humans needs to read it to, is imho a travesty of small mindedness.
    – cmroanirgo
    Commented Jan 21, 2018 at 0:29
  • 36
    @cmroanirgo: You're obviously not the first to complain about that limitation of JSON... that's why we have parsers that silently allow comments, and other formats such as YAML and JSON5. However this doesn't change the fact that JSON is what it is. Rather, I find it interesting that people started using JSON for purposes where it clearly wasn't sufficient in the first place, given the limitation in question. Don't blame the JSON format; blame ourselves for insisting on using it where it isn't a particularly good fit. Commented Jan 21, 2018 at 7:48
1010

Include comments if you choose; strip them out with a minifier before parsing or transmitting.

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. It includes this notable comment from the creator of JSON:

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. - Douglas Crockford, 2012

Hopefully that's helpful to those who disagree with why JSON.minify() could be useful.

20
  • 190
    The only problem I have with JSON.minify() is that it is really really slow. So I made my own implementation that does the same thing: gist.github.com/1170297 . On some large test files your implementation takes 74 seconds and mine 0.06 seconds.
    – WizKid
    Commented Aug 25, 2011 at 9:16
  • 76
    it'd be great if you could submit the suggested alternative algorithm to the github repo for JSON.minify(), so that it can be ported to all the supported langs: github.com/getify/json.minify
    – user228852
    Commented Aug 30, 2011 at 17:20
  • 27
    @MarnenLaibow-Koser there are still valid uses for comments even for data stream (or even packet) usage: inclusion of diagnostics metadata like creation time or sources is common use with XML, and perfectly sensible for JSON data as well. Arguments against comments are shallow, and any textual data format should allow for comments, regardless of implied intended usage (nothing spec suggest JSON can not be used elsewhere, fwiw)
    – StaxMan
    Commented Mar 28, 2014 at 22:09
  • 32
    If JSON is to have universal acceptance (which it basically does) then it should have universal application. Example: JSON can serve as an application configuration file. This application would desire comments.
    – eggmatters
    Commented Jan 27, 2016 at 19:31
  • 24
    To throw my own two cents in, if JSON is supposed to be a pure "data-packet exchange format", then it should've been implemented as a strictly-binary format. As it stands, the data is represented as a human-readable string-based syntax, and it logically follows that anything designed to be readable by humans should also allow for comments.
    – Abion47
    Commented Nov 12, 2018 at 20:20
573

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+

26
  • 307
    I thought JSON was to supposed to be more human readable than, say, XML? Comments are for readability.
    – Intrepidis
    Commented Oct 14, 2012 at 13:00
  • 47
    Anyway, you could be naughty and add parsing directives in the JSON: {"__directives":{"#n#":"DateTime.Now"}, "validdate":"#n#"}... It looks like YAML is the way forward then...
    – Intrepidis
    Commented Oct 14, 2012 at 13:04
  • 122
    Personal opinion: not allowing comments IS lame. I had no option other than building a non-standard JSON parser that ignores comments, to decode my config files.
    – caiosm1005
    Commented Sep 23, 2013 at 2:28
  • 72
    "I removed comments from JSON because I saw people were using them to hold parsing directive". By that logic, he should also have removed the string type. Terrible decision.
    – adelphus
    Commented Jun 12, 2014 at 14:22
  • 134
    That's like requiring all bicycles to have training wheels because some people can't ride bicycles. Removing an important feature because stupid people abuse it is bad design. A data format should prioritize usability over being idiot-proof.
    – Phil Goetz
    Commented May 14, 2015 at 17:24
387

JSON does not support comments. It was also never intended to be used for configuration files where comments would be needed.

Hjson is a configuration file format for humans. Relaxed syntax, fewer mistakes, more comments.

Hjson intro

See hjson.github.io for JavaScript, Java, Python, PHP, Rust, Go, Ruby, C++ and C# libraries.

8
  • 35
    Upvoted. It's obviously a good variation un-open conservative people would just love to hate. I hope your implementation gets known further - and perhaps even gets more popular than the original ;) I hope someone gets to implement it with Ruby as well. @adelphus The language being well-defined is your own perspective or opinion. Being a conservative "developer" if you are one doesn't prove that you are better and you could be even worse keeping yourself locked up in limited spaces. Don't go judging people as terrible developers easily.
    – konsolebox
    Commented Jun 30, 2014 at 19:20
  • 20
    Sorry about that, @konsolebox. Perhaps you might reconsider your "well-defined JSON is your opinion" view after reading ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf It is a real standard and devs implementing their own "special" versions leads to fragmentation, confusion and a lot of wasted time. Look at the mess web developers are left with when writing code just because each browser implements slightly different versions of standards. The JSON language may not be perfect, but fragmentation is worse. And yes, that's just a opinion and you're free to disagree.
    – adelphus
    Commented Jul 9, 2014 at 16:02
  • 35
    I admire your gumption, but you're kinda re-inventing YAML. If you want lot's of flexibility and human readability, use YAML (don't actually: stackoverflow.com/questions/450399/…) or stick with curmudgeony, yet unambiguous JSON.
    – user23987
    Commented Aug 7, 2014 at 18:25
  • 9
    I find the most user-friendly configuration format is still INI. It's straightforward and not very syntax heavy. This makes it less intimidating for users just dipping their toes in the configuration pond.
    – Matt
    Commented Feb 10, 2015 at 15:15
  • 29
    Whenever you need json as config (where comments are needed) - name your file ".js" instead of ".json".. js can of course handle any valid json object and additionally can handle comments.. That's the reason why it is "webpack.config.js" and not "webpack.config.json" (well there's a lot more reasons for that too in webpack :P)
    – jebbie
    Commented Apr 6, 2016 at 14:20
246

DISCLAIMER: YOUR WARRANTY IS VOID

As has been pointed out, this hack takes advantage of the implementation of the spec. Not all JSON parsers will understand this sort of JSON. Streaming parsers in particular will choke.

It's an interesting curiosity, but you should really not be using it for anything at all. Below is the original answer.


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 that JSON parsers work the same way. So we can use this to create comments in the source JSON that will not be present in a 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!

25
  • 182
    From the specification: The names within an object SHOULD be unique.
    – Quentin
    Commented Aug 2, 2013 at 13:50
  • 110
    The order of elements in JSON is not guaranteed. That means the "last" item could change!
    – sep332
    Commented Aug 2, 2013 at 14:33
  • 73
    This clearly violates the spec (see above comments), don't do this. ietf.org/rfc/rfc4627.txt?number=4627
    – voidlogic
    Commented Aug 2, 2013 at 14:39
  • 381
    NO - what if the parser is streaming? What if the parser reads it into a dictionary where key ordering is undefined? kill this with fire. Commented Aug 2, 2013 at 14:55
  • 37
    As we've been working on RFC 4627bis at the IETF in the JSON working group (join us and help! datatracker.ietf.org/wg/json), we have found four different approaches that implementors have used for duplicate names in an object: use the first; use the last; report all of them and let the caller pick one; return an error and stop parsing. If your data can't survive all of those approaches, it won't interoperate in practice. Commented Aug 3, 2013 at 22:03
205

Consider using YAML. It's nearly a superset of JSON (virtually all valid JSON is valid YAML) and it allows comments.

16
  • 23
    @NateS Many people had already pointed out that the answer was no. I suggested a better way to achieve the OP's goal. That's an answer. Commented Mar 28, 2014 at 12:57
  • 6
    @marnen-laibow-koser: yup, it must have been incompetence to use the available YAML libraries for Java and Perl and expect the YAML produced by each to be consumed by the other without error. That YAML interop was an issue, but JSON interop wasn't, is entirely explained by my lack of knowledge.
    – user23987
    Commented Aug 17, 2014 at 23:32
  • 4
    @marnen-laibow-koser, a format that accomplishes the same thing with a simpler spec is better. A pragmatic format with perfect implementations is better than an ideal format with imperfect implementations. Not all the blame for faulty libs lies on the implementors' shoulders; the YAML spec is long, dense, and obtuse. Its Wikipedia entry cites two examples of ambiguities; if one must put an emitter between a human and the format to protect them from ambiguities, the format loses its human friendly claim. JSON claims less and mostly succeeds where YAML claims more and falls short.
    – user23987
    Commented Aug 25, 2014 at 11:45
  • 3
    @marnen-laibow-koser, I've refuted your implication of my own incompetence, backed up my claims with specifics, and elaborated slightly on my preferences/biases that inform my YAML critique. Further comments by myself probably have diminishing returns. I'm confident of future readers' ability to make an informed choice. Aside from skirting close to an ad hominem attack, thank you for the discourse. The last word is yours should you desire it.
    – user23987
    Commented Aug 25, 2014 at 11:56
  • 4
    @toolbear No ad hominem attack was intended. "A pragmatic format with perfect implementations is better than an ideal format with imperfect implementations"—Not sure I agree. If the format is ideal (and implementable), then one can always make a good implementation. If the format isn't ideal, then even a perfect implementation won't be very good. :) "the YAML spec is long, dense, and obtuse"—That's not actually what "obtuse" means, but the YAML spec is quite clear. I don't see any ambiguities mentioned in Wikipedia; please cite specific sections of the article if I missed something. Commented Sep 13, 2014 at 0:58
147

You can't. At least that's my experience from a quick glance at json.org.

JSON has its syntax visualized on that page. There isn't any note about comments.

130

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.

Another parser is JSON5.

An alternative to JSON TOML.

A further alternative is jsonc.

The latest version of nlohmann/json has optional support for ignoring comments on parsing.

3
  • Groovy has some built-in classes for handling JSON. JsonSlurper can handle comments. Of course, comments are not allowed in the official spec, so this behavior in any parser is non-standard and non-portable.
    – izrik
    Commented Nov 6, 2015 at 21:47
  • 2
    Newtonsoft Json.NET also support C-style comments with no problems
    – Max
    Commented Apr 17, 2020 at 1:19
  • IMHO this is the best answer to the question, because it includes a good list of many alternative parsers that do have support. Hacks using duplicate or extraneous keys should not be encouraged, if you want/need comments you should use an alternative standard.
    – Coderer
    Commented Nov 12, 2021 at 9:38
109

Here is what I found in the Google Firebase documentation that allows you to put comments in JSON:

{
  "//": "Some browsers will use this to enable push notifications.",
  "//": "It is the same for all projects, this is not your project's sender ID",
  "gcm_sender_id": "1234567890"
}
4
  • FYI, Firebase Realtime Database does not allow the use of '/' in a key. so this can be a nice convention for your own use, but you cannot do it in Firebase
    – gutte
    Commented Nov 1, 2017 at 20:44
  • 12
    This method breaks some libraries, which require that the key must be unique. I'm working around that issue by numbering the comments.
    – MovGP0
    Commented Jan 19, 2018 at 11:45
  • good comment, I found this question on SO ... this part seems not to be covered by the spec stackoverflow.com/questions/21832701/…
    – mana
    Commented Jan 20, 2018 at 19:36
  • 17
    I tend to use it like this nowadays: { "//foo": "foo comment", "foo": "foo value", "//bar": "bar comment", "bar": "bar value" } You can use an array for multiple comments: { "//foo": [ "foo comment 1", "foo comment 2" ], "foo": ''foo value" }
    – MovGP0
    Commented Mar 9, 2018 at 16:29
97

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.

4
  • 2
    yes, the json-schema google group is fairly active and I would recommend JSV for a good JavaScript implementation of a JSON Schema validator.
    – raffel
    Commented Nov 27, 2012 at 11:34
  • If you use clojure (and I'm sure you don't) there's a reasonably featured open-source JSON schema parser here: github.com/bigmlcom/closchema Commented Apr 15, 2013 at 13:50
  • @Munhitsu Manatee.Json (.Net) extensively supports JSON schema. Commented Jun 26, 2015 at 0:26
  • This isn't relevant for all situations. I have one where I have a manually configured JSON to be parsed by something else (a package manager) that has its own schema. In that I want a comment such as /* It's better to use X instead from another package manager, however that manager doesn't provide X yet so. */.
    – jgmjgm
    Commented Dec 8, 2017 at 11:22
90

NO. JSON used to support comments but they were abused and removed from the standard.

From the creator of 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. - Douglas Crockford, 2012

The official JSON site is at JSON.org. JSON is defined as a standard by ECMA International. There is always a petition process to have standards revised. It is unlikely that annotations will be added to the JSON standard for several reasons.

JSON by design is an easily reverse-engineered (human parsed) alternative to XML. It is simplified even to the point that annotations are unnecessary. It is not even a markup language. The goal is stability and interoperablilty.

Anyone who understands the "has-a" relationship of object orientation can understand any JSON structure - that is the whole point. It is just a directed acyclic graph (DAG) with node tags (key/value pairs), which is a near universal data structure.

This only annotation required might be "//These are DAG tags". The key names can be as informative as required, allowing arbitrary semantic arity.

Any platform can parse JSON with just a few lines of code. XML requires complex OO libraries that are not viable on many platforms.

Annotations would just make JSON less interoperable. There is simply nothing else to add unless what you really need is a markup language (XML), and don't care if your persisted data is easily parsed.

BUT as the creator of JSON also observed, there has always been JS pipeline support for comments:

Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser. - Douglas Crockford, 2012

0
87

If you are using Jackson as your JSON parser then this is how you enable it to allow comments:

ObjectMapper mapper = new ObjectMapper().configure(Feature.ALLOW_COMMENTS, true);

Then you can have comments like this:

{
  key: "value" // Comment
}

And you can also have comments starting with # by setting:

mapper.configure(Feature.ALLOW_YAML_COMMENTS, true);

But in general (as answered before) the specification does not allow comments.

1
  • is this reversible ? what if you load the file and write it back ?
    – R. Du
    Commented Nov 19, 2020 at 18:11
59

If you are using the Newtonsoft.Json library with ASP.NET to read/deserialize you can use comments in the JSON content:

//"name": "string"

//"id": int

or

/* This is a

comment example */

PS: Single-line comments are only supported with 6+ versions of Newtonsoft Json.

Additional note for people who can't think out of the box: I use the JSON format for basic settings in an ASP.NET web application I made. I read the file, convert it into the settings object with the Newtonsoft library and use it when necessary.

I prefer writing comments about each individual setting in the JSON file itself, and I really don't care about the integrity of the JSON format as long as the library I use is OK with it.

I think this is an 'easier to use/understand' way than creating a separate 'settings.README' file and explaining the settings in it.

If you have a problem with this kind of usage; sorry, the genie is out of the lamp. People would find other usages for JSON format, and there is nothing you can do about it.

2
  • 1
    The point is a file with comments is not JSON and will fail to be parsed by many JSON libraries. Feel free to do whatever you want in your own program but a file with comments is not JSON. If you claim it is then people will try to parse it with their language/library of choice and it will fail. It's like asking if you can use square brackets instead of angle brackets in XML. You can do whatever you want but it will no longer be XML.
    – gman
    Commented Jun 6, 2019 at 3:35
  • Could become problematic if the parsers implementation changed. Commented Jan 16, 2022 at 4:28
52

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.

7
  • 3
    Probably the best suggestion so far, though still an issue for keeping files as an interchange format, as they need pre-processing before use.
    – Orbling
    Commented Feb 25, 2011 at 11:04
  • I agree and have written a JSON parser in Java, available at www.SoftwareMonkey.org, that does exactly that. Commented Jul 28, 2012 at 1:51
  • 3
    Despite I think, it is not a good idea to extend JSON (without calling it a different exchange format): make sure to ignore "comments" within strings. { "foo": "/* This is not a comment.*/" }
    – stofl
    Commented Jul 27, 2013 at 12:09
  • 31
    "...would be a one liner" umm, no, actually, JSON is not a regular grammar where a regular expression can simply find matching pairs of /*. You have to parse the file to find if a /* appears inside a string (and ignore it), or if it's escaped (and ignore it), etc. Also, your answer is unhelpful because you simply speculate (incorrectly) rather than providing any solution.
    – user228852
    Commented Dec 8, 2013 at 21:55
  • 1
    What @kyle-simpson said. Also, he's too modest to direct readers to his own answer about using JSON.minify as an alternative to ad hoc regexps. Do that, not this.
    – user23987
    Commented Aug 7, 2014 at 19:32
46

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.

3
  • 28
    It is true that JSON format does not have comments. Personally I think that is a significant mistake -- ability to have comments as metadata (not data) is a very useful thing with xml. Earlier draft versions of JSON specification did include comments, but for some reason they were dropped. :-/
    – StaxMan
    Commented Sep 1, 2009 at 18:20
  • 7
    @StaxMan they were dropped exactly because people started using them as metadata. Crockford said it breaked the compatibility for what the format was designed, and I agree: if you want metadata, why not include it as actual data? It's even easier to parse this way. Commented Dec 11, 2010 at 9:03
  • 8
    Metadata belongs in metadata constructs (e.g. HTML <meta> tags), not comments. Abusing comments for metadata is just a hack used where no true metadata construct exists. Commented Sep 6, 2011 at 4:55
46

Other answers state that JSON does not support comments, but this is partially untrue: the spec author Douglas Crokford clarified that a JSON decoder may accept comments as long as they are just discarded.

Hence, it's perfectly fine and an accepted use case for you to make your own JSON decoder or at least preprocessor that accepts comments to then just strip them out (as long as you just ignore comments and don't use them to guide how your application should process the JSON data). This is for example indicated for configuration files stored in JSON, as @toolbear comments below. Obviously, since JSON is primarily meant as a data transmission format, and hence as sparse as possible, if you transmit a JSON file with comments, it's better to strip out comments before to save network bandwidth.

Source:

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.

Douglas Crockford, author of JSON spec, in a post in a forum thread in 2005.

1
  • 5
    Crockford later went on to write: "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." See @kyle-simpson's answer about JSON.minify for more info.
    – user23987
    Commented Aug 7, 2014 at 19:14
43

Yes, the new standard, JSON5 allows the C++ style comments, among many other extensions:

// A single line comment.

/* A multi-
   line comment. */

The JSON5 Data Interchange Format (JSON5) is a superset of JSON that aims to alleviate some of the limitations of JSON. It is fully backwards compatible, and using it is probably better than writing the custom non standard parser, turning non standard features on for the existing one or using various hacks like string fields for commenting. Or, if the parser in use supports, simply agree we are using JSON 5 subset that is JSON and C++ style comments. It is much better than we tweak JSON standard the way we see fit.

There is already npm package, Python package, Java package and C library available. It is backwards compatible. I see no reason to stay with the "official" JSON restrictions.

I think that removing comments from JSON has been driven by the same reasons as removing the operator overloading in Java: can be used the wrong way yet some clearly legitimate use cases were overlooked. For operator overloading, it is matrix algebra and complex numbers. For JSON comments, its is configuration files and other documents that may be written, edited or read by humans and not just by parser.

5
  • 1
    Is JSON5 "very" standard? Or still being adopted? I mean... May I expect that any framework in 2021 will understand Json5? Or most probably not? Commented Mar 28, 2021 at 13:53
  • If you create your own standard, you are the only in the world using it. Something like JSON5 is probably better. Commented Mar 28, 2021 at 21:09
  • Not meant to create my standard... just wondering if it's time to consider JSON5 or better stick to "old JSON" and wait a few months yet before devoting time to exploration. Commented Mar 29, 2021 at 19:00
  • 2
    JSON5 is not "the new standard" - It's a separate standard developed by separate people.
    – zkldi
    Commented Aug 3, 2021 at 16:51
  • 1
    This misleadingly implies that JSON5 is a new json-version, while it is actually more like a fork. Json does not have comments, and it never will, because it is so widely used for data interchange that breaking existing parsers is not an option.
    – julaine
    Commented May 27 at 7:18
39

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!

1
  • No need to fragment JSON. JSON with comments is no longer JSON. But it's perfectly acceptable to annotate your JSON with comments, so long as you make sure to strip them out before parsing or transmitting it. It should never be the receiver's responsibility to do this.
    – user23987
    Commented Aug 7, 2014 at 19:19
38

I just encountering this for configuration 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 it is way less verbose and more human readable - and parsers are easy and ubiquitous in many languages. It's just a tree of data. But out-of-band comments are a necessity often to document "default" configurations and the like. Configurations 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.

4
  • 5
    For config files, I'd suggest YAML, not JSON. It's (almost) a more powerful superset of JSON, but supports more readable constructs as well, including comments. Commented Oct 19, 2011 at 21:35
  • @Hamidam Over a dozen languages support yaml: yaml.org - but you're right to ask how many have support built-in, without the need for a third-party library dependency. Looks like Ruby 1.9.2 does. Anyone know of others? And which languages ship support for json by default?
    – nealmcb
    Commented Mar 21, 2012 at 15:53
  • 5
    YAML interop is a lie: stackoverflow.com/questions/450399/… . If your instinct is to use JSON for configuration files, follow it.
    – user23987
    Commented Aug 7, 2014 at 19:10
  • Yaml has wide support, but the spec is complex and leads to bugs and arbitrary code execution. YAML: probably not so great after all, noyaml, and The yaml document from hell chronicle the flaws of yaml.
    – idbrii
    Commented Oct 12, 2023 at 21:39
38

It depends on your JSON library. Json.NET supports JavaScript-style comments, /* commment */.

See another Stack Overflow question.

1
  • And I believe that is why I see a comment in a screenshot on this ASP.NET vNext preview page (under package.json): blogs.msdn.com/b/webdev/archive/2014/06/03/… although I haven't found anything in the spec yet.
    – webXL
    Commented Sep 17, 2014 at 21:54
37

If you use JSON5 you can include comments.


JSON5 is a proposed extension to JSON that aims to make it easier for humans to write and maintain by hand. It does this by adding some minimal syntax features directly from ECMAScript 5.

0
28

The Dojo Toolkit JavaScript toolkit (at least as of version 1.4), allows you to include comments in your JSON. The comments can be of /* */ format. Dojo Toolkit consumes the JSON via the dojo.xhrGet() call.

Other JavaScript toolkits may work similarly.

This can be helpful when experimenting with alternate data structures (or even data lists) before choosing a final option.

4
  • 4
    No. Not this. JSON doesn't have comments. If you choose to annotate your JSON with comments, minify it before parsing or transmitting. This shouldn't be the receiver's responsibility.
    – user23987
    Commented Aug 7, 2014 at 19:31
  • 3
    I didn't say that JSON has comments. Neither did I mean to imply that it's appropriate to include them in your JSON, especially in a production system. I said that the Dojo toolkit permits you to add them, which is (or at least, was) factually true. There are very helpful use-cases out there for doing so in your testing phase.
    – David
    Commented Aug 7, 2014 at 23:37
  • 1
    It's bad voodoo to serve up commented, and thus invalid JSON, which dojo.xhrGet() implicitly encourages by accepting.
    – user23987
    Commented Aug 8, 2014 at 20:21
  • I still vote for upgrading the JSON spec to allow comments. I'm all for minifying and stripping the comments before transmitting the JSON, but not having any ability to comment your JSON in any standard way without having to pass it through a separate utility before parsing it just seems silly. I also makes it impossible to use a JSON editor on your JSON configuration files, because your files are not valid JSON. Commented Sep 15, 2014 at 7:03
28

Disclaimer: This is silly

There is actually a way to add comments, and stay within the specification (no additional parser needed). It will not result into human-readable comments without any sort of parsing though.

You could abuse the following:

Insignificant whitespace is allowed before or after any token. Whitespace is any sequence of one or more of the following code points: character tabulation (U+0009), line feed (U+000A), carriage return (U+000D), and space (U+0020).

In a hacky way, you can abuse this to add a comment. For instance: start and end your comment with a tab. Encode the comment in base3 and use the other whitespace characters to represent them. For instance.

010212 010202 011000 011000 011010 001012 010122 010121 011021 010202 001012 011022 010212 011020 010202 010202

(hello base three in ASCII) But instead of 0 use space, for 1 use line feed and for 2 use carriage return.

This will just leave you with a lot of unreadable whitespace (unless you make an IDE plugin to encode/decode it on the fly).

I never even tried this, for obvious reasons and neither should you.

0
28

JSON doesn't allow comments, per se. The reasoning is utterly foolish, because you can use JSON itself to create comments, which obviates the reasoning entirely, and loads the parser data space for no good reason at all for exactly the same result and potential issues, such as they are: a JSON file with comments.

If you try to put comments in (using // or /* */ or # for instance), then some parsers will fail because this is strictly not within the JSON specification. So you should never do that.

Here, for instance, where my image manipulation system has saved image notations and some basic formatted (comment) information relating to them (at the bottom):

{
    "Notations": [
        {
            "anchorX": 333,
            "anchorY": 265,
            "areaMode": "Ellipse",
            "extentX": 356,
            "extentY": 294,
            "opacity": 0.5,
            "text": "Elliptical area on top",
            "textX": 333,
            "textY": 265,
            "title": "Notation 1"
        },
        {
            "anchorX": 87,
            "anchorY": 385,
            "areaMode": "Rectangle",
            "extentX": 109,
            "extentY": 412,
            "opacity": 0.5,
            "text": "Rect area\non bottom",
            "textX": 98,
            "textY": 385,
            "title": "Notation 2"
        },
        {
            "anchorX": 69,
            "anchorY": 104,
            "areaMode": "Polygon",
            "extentX": 102,
            "extentY": 136,
            "opacity": 0.5,
            "pointList": [
                {
                    "i": 0,
                    "x": 83,
                    "y": 104
                },
                {
                    "i": 1,
                    "x": 69,
                    "y": 136
                },
                {
                    "i": 2,
                    "x": 102,
                    "y": 132
                },
                {
                    "i": 3,
                    "x": 83,
                    "y": 104
                }
            ],
            "text": "Simple polygon",
            "textX": 85,
            "textY": 104,
            "title": "Notation 3"
        }
    ],
    "imageXW": 512,
    "imageYW": 512,
    "imageName": "lena_std.ato",
    "tinyDocs": {
        "c01": "JSON image notation data:",
        "c02": "-------------------------",
        "c03": "",
        "c04": "This data contains image notations and related area",
        "c05": "selection information that provides a means for an",
        "c06": "image gallery to display notations with elliptical,",
        "c07": "rectangular, polygonal or freehand area indications",
        "c08": "over an image displayed to a gallery visitor.",
        "c09": "",
        "c10": "X and Y positions are all in image space. The image",
        "c11": "resolution is given as imageXW and imageYW, which",
        "c12": "you use to scale the notation areas to their proper",
        "c13": "locations and sizes for your display of the image,",
        "c14": "regardless of scale.",
        "c15": "",
        "c16": "For Ellipses, anchor is the  center of the ellipse,",
        "c17": "and the extents are the X and Y radii respectively.",
        "c18": "",
        "c19": "For Rectangles, the anchor is the top left and the",
        "c20": "extents are the bottom right.",
        "c21": "",
        "c22": "For Freehand and Polygon area modes, the pointList",
        "c23": "contains a series of numbered XY points. If the area",
        "c24": "is closed, the last point will be the same as the",
        "c25": "first, so all you have to be concerned with is drawing",
        "c26": "lines between the points in the list. Anchor and extent",
        "c27": "are set to the top left and bottom right of the indicated",
        "c28": "region, and can be used as a simplistic rectangular",
        "c29": "detect for the mouse hover position over these types",
        "c30": "of areas.",
        "c31": "",
        "c32": "The textx and texty positions provide basic positioning",
        "c33": "information to help you locate the text information",
        "c34": "in a reasonable location associated with the area",
        "c35": "indication.",
        "c36": "",
        "c37": "Opacity is a value between 0 and 1, where .5 represents",
        "c38": "a 50% opaque backdrop and 1.0 represents a fully opaque",
        "c39": "backdrop. Recommendation is that regions be drawn",
        "c40": "only if the user hovers the pointer over the image,",
        "c41": "and that the text associated with the regions be drawn",
        "c42": "only if the user hovers the pointer over the indicated",
        "c43": "region."
    }
}
2
  • The reasoning is not foolish, and you just proved it. Implementing comments as tags preserves interoperability. This is exactly why Crockford wanted comments to be parsed as tags. Now everything is just a tag and parsed the same way. Commented Jul 14, 2019 at 16:30
  • 2
    If the spec stated that "a line beginning with # is a comment", then that would be fully interoperable. As it stands, comments both load the parser space, as they are valid parsed items rather than understood to be comments, and they can be different for every .json file in existence. Whereas if (for instance) the spec said "lines beginning with # are comments", then the parsers could skip those lines without parsing (faster) and not load the parser space (better memory utilization.) There's no benefit at all from the lack of comments in .json, only downsides.
    – fyngyrz
    Commented Jan 28, 2020 at 14:41
27

JSON is not a framed protocol. It is a language free format. So a comment's format is not defined for JSON.

As many people have suggested, there are some tricks, for example, duplicate keys or a specific key _comment that you can use. It's up to you.

27

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.

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.

26

This is a "can you" question. And here is a "yes" answer.

No, you shouldn't use duplicative object members to stuff side channel data into a JSON encoding. (See "The names within an object SHOULD be unique" in the RFC).

And yes, you could insert comments around the JSON, which you could parse out.

But if you want a way of inserting and extracting arbitrary side-channel data to a valid JSON, here is an answer. We take advantage of the non-unique representation of data in a JSON encoding. This is allowed* in section two of the RFC under "whitespace is allowed before or after any of the six structural characters".

*The RFC only states "whitespace is allowed before or after any of the six structural characters", not explicitly mentioning strings, numbers, "false", "true", and "null". This omission is ignored in ALL implementations.


First, canonicalize your JSON by minifying it:

$jsonMin = json_encode(json_decode($json));

Then encode your comment in binary:

$hex = unpack('H*', $comment);
$commentBinary = base_convert($hex[1], 16, 2);

Then steg your binary:

$steg = str_replace('0', ' ', $commentBinary);
$steg = str_replace('1', "\t", $steg);

Here is your output:

$jsonWithComment = $steg . $jsonMin;
4
  • 2
    The RFC only states "whitespace is allowed before or after any of the six structural characters", not explicitly mentioning strings, numbers, "false", "true", "null". This omission is ignored in ALL implementations. Commented Sep 24, 2014 at 18:15
  • 1
    For greater comment density, couldn't you encode your comment in ternary and use space, tab, and newline to steg it? Commented Sep 26, 2018 at 19:44
  • SHOULD is not MUST. See the explicitly included RFC 2119: MUST: This word, or the terms "REQUIRED" or "SHALL", mean that the definition is an absolute requirement of the specification. ... SHOULD: This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.
    – Jeff K
    Commented Sep 23, 2019 at 18:04
  • 2
    Good reference. A better reasoning against using duplicated keys is the standard's quote "When the names within an object are not unique, the behavior of software that receives such an object is unpredictable.". Also now I understand why the standard was not "MUST be unique," this makes a validator simpler, it only needs to track [ and {, it does not need to know which keys were used already. Commented Sep 26, 2019 at 20:22
25

In my case, I need to use comments for debug purposes just before the output of the JSON. So I put the debug information in the HTTP header, to avoid breaking the client:

header("My-Json-Comment: Yes, I know it's a workaround ;-) ");

Enter image description here

1
  • 1
    I was just about to post the same suggestion. I think this is a not overly hacky way to communicate something. Better than keeping a variable and injecting it into the payload.
    – Alien426
    Commented May 14 at 7:10
17

We are using strip-json-comments for our project. It supports something like:

/*
 * Description 
*/
{
    // rainbows
    "unicorn": /* ❤ */ "cake"
}

Simply npm install --save strip-json-comments to install and use it like:

var strip_json_comments = require('strip-json-comments')
var json = '{/*rainbows*/"unicorn":"cake"}';
JSON.parse(strip_json_comments(json));
//=> {unicorn: 'cake'}
3
  • 2
    Note that the json is not a valid JSON anymore when it includes these propriety comments.
    – Roy Prins
    Commented Jul 31, 2019 at 12:12
  • In which context does strip-json-comments run? Node.js? Commented Oct 8, 2020 at 17:06
  • @PeterMortensen i tried for node.js. you can try whether works on client-side js.
    – Joy
    Commented Oct 8, 2020 at 23:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.