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

95 upvote
  flag
@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. – Michael Burr
12 upvote
  flag
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. – hangtwenty
upvote
  flag
and perhaps this is one reason why TOML was created.. – Alex Nolasco
5 upvote
  flag
Slightly noobish but ,i also tried using // for comments in JSON. Now I realize it is strictly used for interchange/exchange. Sigh! I cant comment any more :(. Life is doomed!. – Sid
upvote
  flag
Check out highcharts.com/samples/data/…? and you will see comments. This is JSONP, though, not pure JSON. See my response below. – osa
upvote
  flag
@fonzo-highway Change your username and the next will ask "Who is fonzo-highway?" :o) – Sir Rufo
upvote
  flag
@DavePeck I'd say that's a good time to get started on an Objective-C binding for YAML and forget all the cruft you used to have to type to manually write JSON. – nus
upvote
  flag
JSON5 supports comments: //allinonescript.com/a/7901053/108238 – schoetbi
upvote
  flag
Ruby's json parser is another example of a parser that supports comments. – Ben Crowell
upvote
  flag
I dont understand why anyone would ever need that – Tom Doodler
upvote
  flag
If you want a language for configuration with comments see TOML – schoetbi
upvote
  flag
Comments are not permitted because it's too late to support comments. Major oversight. Ironically, YAML supports comments. – bvj
upvote
  flag
oreilly.com/learning/adding-comments-in-json has 2 ways to do add a comment functionality to your JSON file – Flotolk

42 Answers 11

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.

up vote 3645 down vote accepted

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 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"
            }
         }
      }
   }
}
132 upvote
  flag
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...", – Rob Fonseca-Ensor
257 upvote
  flag
A fairly recent explanation/rationale for why there are no comments in JSON (or more accurately, why they were removed early on): plus.google.com/118095276221607585885/posts/RK8qyGVaGSr Also see, tech.groups.yahoo.com/group/json/message/156 and other discussion in that thread. – Michael Burr
10 upvote
  flag
BTW, the json library for Java google-gson has support for comments. – centic
6 upvote
  flag
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 – Juan Mendes
upvote
  flag
@JuanMendes: you are allowed to have the same key multiple times. – progo
upvote
  flag
We can to select more unique comment keys format for this. Something like {"<!-- glossary -->": "Comment text"} looks ok. "/* glossary */" too. – vp_arth
upvote
  flag
Why is GlossList not an array (GlossList: [ { .. }, { .. } ])? – Luca Steeb
upvote
  flag
If you're using a schema to validate the JSON, it may fail due to the extra fields. – gregsdennis
13 upvote
  flag
you could also use "//": this looks more native and is still repeatable in the same parent – smnbbrv
1 upvote
  flag
@JuanMendes Probably far too late to be of help, but for multi-line comments, make the value of the comment element an array of strings: [ "line 1", <CRLF> "line 2", <CRLF> "line 3" ]. – TripeHound
1 upvote
  flag
The thing is it changes the semantic of the JSON, e.g. changing the length of an array. – Elgs Qian Chen
upvote
  flag
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. – Петър Петров
upvote
  flag
There is JSON5 (5 referring to ECMAScript 5 (and later)). – Peter Mortensen
upvote
  flag
There are a number of libraries and frameworks that now support comments in JSON files. In C# land, Newtonsoft's JSON.Net supports them, and as a result you'll observe comments used in various JSON's throughout .Net Core configuration files. – Ken Mason
upvote
  flag
If you are returning the json via api then the client should be using the HTTP Options verb to read the json descriptions/comments – MIKE
upvote
  flag
XML wants its document back. – jwg

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.

11 upvote
  flag
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
3 upvote
  flag
@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. – Camilo Martin
3 upvote
  flag
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. – Marnen Laibow-Koser
upvote
  flag
That's exactly the reason why it was dropped: comments used as metadata would break interoperability. You should just store your meta-data as JSON too. – gaborous
upvote
  flag
This answer is redundant with better written, higher upvoted answers, that say essentially the same thing, even though this may have been written earlier. Cest la vie. – toolbear

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.

1 upvote
  flag
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
upvote
  flag
I agree and have written a JSON parser in Java, available at www.SoftwareMonkey.org, that does exactly that. – Lawrence Dol
2 upvote
  flag
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
20 upvote
  flag
"...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. – Kyle Simpson
1 upvote
  flag
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. – toolbear

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.

123 upvote
  flag
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
36 upvote
  flag
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 – Kyle Simpson
3 upvote
  flag
Perl's JSON supports # comments. – Johannes Ernst
2 upvote
  flag
Comments do not make sense in JSON. JSON is not meant to be a file format, just a data-packet interchange format. If you need something like commented JSON, use YAML instead. – Marnen Laibow-Koser
upvote
  flag
@Viktor Why would you need comments in a data packet? That wastes space. If for didactic purposes, just put them elsewhere, or accept that you're breaking the format. In an actual application, they shouldn't be necessary. – Marnen Laibow-Koser
2 upvote
  flag
You might find it interesting to hear, from the author of JSON, why comments were left out of the spec: youtu.be/-C-JoyNuQJs?t=48m53s – MiniGod
12 upvote
  flag
@MiniGod I have already heard Doug's thoughts on this topic many times. I addressed them long ago in my blog post: blog.getify.com/json-comments – Kyle Simpson
11 upvote
  flag
@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
1 upvote
  flag
@StaxMan No. Comments in a data stream are just wasted bytes. If metadata like creation time can't be inferred from the stream itself, then why not make it actual, parseable content in the stream? Arguments for comments are shallow: if something is worth including, then it's worth including it as data. – Marnen Laibow-Koser
upvote
  flag
@StaxMan I believe I'm backing up everything I say with facts, so as not to make it just my personal opinion. If there's anything I haven't backed up sufficiently, let me know. "Your claim that all metadata ought to be data is just nonsense" No, you're demonstrably wrong here. The only reason to include metadata, I think, is so it can be parsed. If it's going to be parsed, then just make it real data, not comments. Do you have a use case in mind for which this won't work? – Marnen Laibow-Koser
upvote
  flag
@StaxMan "most other text formats recognize this much (XML and YAML have comments)" XML and YAML are designed for files; JSON was simply extracted from JavaScript, and I think it makes a horrible file syntax (YAML and even XML work better in this case). It's true that JSON files may occasionally need comments, but JSON files are themselves a bad idea when YAML does the same job better. :) – Marnen Laibow-Koser
2 upvote
  flag
My canonical use case are log files that are streamed over to be aggregated or stored; so stream/file distinction is virtual and transient. As to skipping: all properties are visible, and there are two main ways to deal with it -- (a) classical, you must know what everything is (to the degree at least that you can skip it), or (b) "anything goes", i.e. just use what you know. It is only trivial to skip metadata in latter case. But I see that you can not conceive of the simple notion of diagnostics-only comments -- no point in arguing past each other here. – StaxMan
upvote
  flag
@StaxMan "My canonical use case are log files"—problematic in itself; JSON is not a good format for logging (too much punctuation compared to YAML or XML). "It is only trivial to skip metadata in latter case."—That's a strong argument for not using the "classical" method (in general, it's too easy to break it). "But I see that you can not conceive of the simple notion of diagnostics-only comments"—What do you mean by diagnostics-only comments? I can't conceive of it if you don't explain it. :) – Marnen Laibow-Koser
3 upvote
  flag
JSON has too much punctuation compared to XML? Can you clarify what you mean there? Here is an example JSON for loading fixtures in Django: [{ "model": "foo.bar", "pk": 1, "fields": { "name": "foo", "customer_number": 12345 }}] The same in XML comes to something like this: <?xml version="1.0" encoding="utf-8"?><django-objects version="1.0"><object pk="1" model="foo.bar"><field type="TextField" name="name">foo</field><field type="IntegerField" name="customer_number">12345</field></object></django-object‌​s> – ManicDee
upvote
  flag
@ManicDee You're right about the punctuation in XML; I was trying to be brief and wound up being inaccurate in that respect. Revised statement: JSON has too much punctuation compared to YAML, and is a poor file-oriented syntax compared to either YAML or XML. (For the record, I'd pick JSON for streams, YAML for files, and XML for nothing every time, unless there's a specific external need for XML.) – Marnen Laibow-Koser
2 upvote
  flag
The problem with this answer is that JSON is a serialization format, and so a minifier has to be written for every language (or a built-in minifier for every parser). How am I supposed to find a json minifier for c now? – Blake
10 upvote
  flag
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
upvote
  flag
@KyleSimpson 404 on your blog link, update the link if you a new copy – Srinath Ganesh
upvote
  flag
The blog post link ("comments make sense in JSON") is broken: Server not found. Can you update your answer (e.g. remove the link, etc. if there isn't a new location for the blog post)? – Peter Mortensen
upvote
  flag
blog post link fixed. – Kyle Simpson
upvote
  flag
This answer abuses the comment by Crockford - jsmin is a javacript minifier, not a JSON minifier. a javascript minifier accepts javascript as input, not JSON, and as such, supports comments. The comment by Crockford in no way can be twisted to mean that comments in JSON are ok, or a JSON minifier should support comments. At best, it's an extension, at worst, it's a security bug, and as such, the backlash is understandable and using Crockfords comment to justify it is a bug. – Marc Lehmann
1 upvote
  flag
Interesting the removal of commenting ability from JSON. Everywhere and always I am reminded to comment my code. Now I have a huge config/data file in JSON that cannot be commented for future reference because for some reason someone thought commenting unnecessary/silly. – JayJay123

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 upvote
  flag
Is JSON schema alive? It exists but is it supported by any known library? – Munhitsu
1 upvote
  flag
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
4 upvote
  flag
This only helps with structured documentation, not ad-hoc documentation – Juan Mendes
upvote
  flag
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 – charleslparker
upvote
  flag
@Munhitsu Manatee.Json (.Net) extensively supports JSON schema. – gregsdennis
upvote
  flag
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

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

  • http://www.json.org
  • RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON)
  • RFC 7159 The JavaScript Object Notation (JSON) Data Interchange Format - Obsoletes: 4627, 7158
44 upvote
  flag
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. – toolbear
21 upvote
  flag
@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. – stakx
upvote
  flag
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
upvote
  flag
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
upvote
  flag
@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. – stakx

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.

2 upvote
  flag
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. – toolbear
1 upvote
  flag
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
upvote
  flag
It's bad voodoo to serve up commented, and thus invalid JSON, which dojo.xhrGet() implicitly encourages by accepting. – toolbear
upvote
  flag
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. – Craig

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.

3 upvote
  flag
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. – Marnen Laibow-Koser
1 upvote
  flag
how many languages do you think supports YAML out of the box compared to json ? – momomo
upvote
  flag
@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
5 upvote
  flag
YAML interop is a lie: //allinonescript.com/questions/450399/… . If your instinct is to use JSON for configuration files, follow it. – toolbear
upvote
  flag
This is old, but I believe that using # is not a good idea. Json is close to the syntax of a Javascript litteral. Javascript supports 2 types of comment : // and /* ... */ If I were you I would stick with one or both these types of comments. – Pascal Ganaye

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

1 upvote
  flag
Note that the converse is not true (valid YAML !=> valid JSON) – g33kz0r
10 upvote
  flag
@g33kz0r Correct, hence my description of YAML as a near-superset of JSON. – Marnen Laibow-Koser
12 upvote
  flag
@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. – Marnen Laibow-Koser
3 upvote
  flag
Downside: yaml library isn't shipped with Python. – Bleeding Fingers
4 upvote
  flag
@BleedingFingers So install it... – Marnen Laibow-Koser
2 upvote
  flag
Agreed that this is a relevant alternative. Nevertheless, don't use YAML if you were already leaning towards JSON: //allinonescript.com/questions/450399/… – toolbear
upvote
  flag
@toolbear: your linked comment suggests you don't know how to use YAML well. I've never had YAML bite me, ever. So yes, use YAML, even if you were already leaning towards JSON. – Marnen Laibow-Koser
4 upvote
  flag
@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. – toolbear
upvote
  flag
@toolbear Sounds like the fault of poorly written libraries; don't blame the format for that. And yeah, your claim of quoting ambiguities suggests lack of knowledge, though I'd be interested in looking at a particular case if you have one. However, the lack of knowledge might be on the part of the parser implementer, not necessarily you. – Marnen Laibow-Koser
2 upvote
  flag
@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. – toolbear
3 upvote
  flag
@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. – toolbear
1 upvote
  flag
@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. – Marnen Laibow-Koser
1 upvote
  flag
yaml >> json . And python has a good yaml library. I have to roll my own in Scala - but still worth it. – javadba

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.

upvote
  flag
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

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+

127 upvote
  flag
I thought JSON was to supposed to be more human readable than, say, XML? Comments are for readability. – Chris Nash
14 upvote
  flag
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... – Chris Nash
2 upvote
  flag
Removing /* */ comments also made JSON a better subset of YAML. – Schwern
1 upvote
  flag
@Schwern But YAML does allow # comments, so your point is kind of muoot – Juan Mendes
1 upvote
  flag
@JuanMendes I don't understand why that makes my point about JSON/YAML compatibility moot. What do you think my point was? – Schwern
upvote
  flag
@Schwern I took your point to be it shouldn't have comments because it makes it not a subset of YAML. I'm saying that YAML does have comments, so it seems wrong to use that as a reason why you wouldn't have comments in JSON. – Juan Mendes
4 upvote
  flag
@JuanMendes Not so much "shouldn't" as it simply is a benefit of the change (personally I find it a pain that I can't comment in JSON files). Keep in mind that JSON is also a subset of Javascript, and YAML and Javascript have mutually incompatible comment syntax. YAML uses # but Javascript uses // and /* */. JSON can't use # as a comment without becoming incompatible with Javascript. JSON can't be a subset of both YAML and Javascript and have comments. – Schwern
9 upvote
  flag
As liz lemon would say… "deal breaker, ladies"! jesus… so to test something with a line "omitted", aka "commented" (in the normal universe).. you have to DELETE the line? no thanks! gimme some good ole' rackety-brackety XML, any day! – Alex Gray
upvote
  flag
@ChrisNash It was not meant to be more readable than XML, just easily readable by humans. json.org And, JSON is easily readable by humans. Comments add additional information, but don't make it any more or less easy to read for humans. – Oscar Godson
47 upvote
  flag
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
1 upvote
  flag
@caiosm1005 Writing own parser for well-defined format is always less-than-perfect. I found that formats like Java properties or plain old INI are far more suitable for configuration files. Java, C++, Python and nodejs all have built-in or library support for one or the other. I especially favor the INI files. It's either that or always supplement configs with a robust readme file. – Artur Czajka
13 upvote
  flag
@ArturCzajka I still dislike the fact JSON doesn't support comments, but I gave INI a try and I must admit it makes much more sense to use them over JSON for config files. Thanks for the response and hopefully more people will change their minds as they read this conversation. (making a parser was more of an exercise anyway :) – caiosm1005
8 upvote
  flag
Classic. I don't buy the argument that you must limit usability because someone might misuse a feature. That's simply dogmatic and short-sighted. The right thing to do is create a mechanism for including comments in JSON, just like every other language. We shouldn't be wasting bandwidth on a pointless philosophical jihad about maintaining "purity". Get over it, add comments, move on. – rakehell
9 upvote
  flag
"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
upvote
  flag
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. – toolbear
9 upvote
  flag
Who flippin' cares if someone was using comments in their JSON to include parsing directives? Honestly. Ridiculous. So, if you put non-standard parsing directives for your own parser in a comment, a parser that follows the official spec will ignore them. Otherwise, people will either not use JSON, or resort to hacks to include comments as data, which is surely no better than having custom parsing directives in the comments. For that matter, people will also put their custom parsing directives into the JSON stream as data. It's a silly argument, and the inability to use comments is obnoxious. – Craig
upvote
  flag
Honestly; has nobody ever used comments in XML for their own custom processing directives? Did it destroy XML interoperability? Has there ever been another language or data format that allow for comments in the file? – Craig
3 upvote
  flag
Not having comments in JSON feels wrong. Formatting (spaces, linefeeds) are allowed in JSON and there is no fundamental difference between formatting and comments. – Johannes Overmann
37 upvote
  flag
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
upvote
  flag
@PhilGoetz But that specific model has training wheels. The analogy would work better with a tricycle. If you don't like it, use another like YAML or a properties file. Not everything should be designed to grasp every possible features you can think about. – Winter
upvote
  flag
The whole point of JSON is that it contains only data. If you feel the need for comments, you should be using XML, not JSON. Same goes for processing instructions (XML has them too). Really, really...if you're using JSON for anything other than rectangular data (rows and cols), then you're probably wrong and should be using XML. – Peter Flynn

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

See another Stack Overflow question.

upvote
  flag
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

Sorry, we can't use comments in JSON... See the syntax diagram for JSON on JSON.org.

Douglas Crockford says "why he removed comments in JSON and providing an alternative 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.

upvote
  flag
I believe what you are referring to is just text annotation for documentation purpose. It's not what is actually returned by the web service. – HoLyVieR
upvote
  flag
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. – toolbear
5 upvote
  flag
This answer duplicates @ArturCzajka who posted the same quote a year before. – kenorb

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!

upvote
  flag
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. – toolbear

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.

3 upvote
  flag
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. – toolbear

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!

136 upvote
  flag
From the specification: The names within an object SHOULD be unique. – Quentin
1 upvote
  flag
Right, but it's not a syntax error, and all the implementations handle it the same. So I think it's pretty safe to use. Not philosophically, but practically. – Ped
93 upvote
  flag
"all the implementations handle it the same" — That's a difficult thing to prove. – Quentin
85 upvote
  flag
The order of elements in JSON is not guaranteed. That means the "last" item could change! – sep332
1 upvote
  flag
@sep332 they are in the case of a hand edited json/config file. – Tracker1
7 upvote
  flag
@Quentin from the rfc2119: "3. 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." – erdeszt
6 upvote
  flag
@Tracker1 — The order is not guaranteed, because what matters is the parser not the person writing the file. The JSON specification doesn't describe what should happen if there are duplicate keys (it says that you SHOULD make them unique), so some parsers might take the first while others might take the last while others fall over. – Quentin
58 upvote
  flag
This clearly violates the spec (see above comments), don't do this. ietf.org/rfc/rfc4627.txt?number=4627 – voidlogic
2 upvote
  flag
@erdeszt — Yes, the full implications must be understood. There is no way to understand those without testing every JSON parser (and since people will keep writing new ones …). – Quentin
6 upvote
  flag
It would be totally reasonable for a parser to discard values of existing keys instead of overwriting them. – Gipsy King
5 upvote
  flag
There are over a hundred different implementations currently listed at json.org. I bet at least one of them doesn't handle it the same. – nemetroid
8 upvote
  flag
I once had quite some trouble with JSON files that had double keys just because it was not explicitely disallowed in the spec. Please don't advise others to do this. – opyh
4 upvote
  flag
My own implementation (for an embedded system, couldn't find an existing one that matched the requirements) always takes the first key in case of duplicates. You really can't assume this will work. – pdw
290 upvote
  flag
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. – deanWombourne
2 upvote
  flag
@Quentin I'm just saying that the spec isn't clear about how to handle this case and this is a clever hack which is "legal" but of course discouraged. – erdeszt
16 upvote
  flag
Downvoted. This is a bad idea, pure and simple. You're abusing a gray area of the JSON specification and it is irresponsible to be promoting such a practice to others. It's a hack; don't do it. – Brad Choate
10 upvote
  flag
You're begging for this to blow up in your face. Like others mentioned, a parser may outright reject your JSON, echo back the "comment" instead of the value, or fail in mysterious ways, like pushing two events for the same key (streaming parsers, most likely). For example, the recent APK signature vulnerability was essentially exploiting the same thing, undefined behavior for multiple non-unique keys (file names), just in zip instead of JSON. – nmaier
9 upvote
  flag
That is wrong on so many levels I don't even know where to begin. I'll just put that here - pragprog.com/the-pragmatic-programmer/extracts/coincidence - and try to forget what I just saw. – Geoffrey Bachelet
3 upvote
  flag
See this question for error case: //allinonescript.com/questions/4912386/… – Paul Tyng
3 upvote
  flag
Bad idea - leads to confusion, against spec, not future proof and JSLint disqualifies the JSON. – Praveen Vijayan
1 upvote
  flag
This is a great hack in todays context. JSON parsing is streamlined both on the server side and browser side. All browsers after and including IE8 support JSON.parse. So really everybody should be using the built in JSON parse. You will use a custom parser for legacy reasons only. And it is highly unlikely the built in JSON parser will change its behaviour and break backward compatibility. – Santosh
upvote
  flag
... continued from above comment by me. The only thing we need to do now is to standardise it so that it is not confusing to the user. For example we could indicate that it is a comment by doing something like "** this is a comment **" – Santosh
19 upvote
  flag
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. – Joe Hildebrand
2 upvote
  flag
Bad hack. It's JSON parser matter. At least IAM policy file (AWS) doesn't accept duplicate JSON key. microsofttranslator.com/bv.aspx?from=&to=en&a=http://… – kyanny
8 upvote
  flag
This is one of the worst answers I've ever seen on stackoverflow. It can break at any time and it is not so smart as it doesn't make it especially readable like regular comments. One may always wonder if we have an item that is a comment or a real piece of data. JSMin seems like a much cleaner (and more readable) solution. That said, the IT industry should still thank you for the joke. – Jeremyfa
upvote
  flag
Solr uses multiple Keys. This is incompatible with the major opensource search server!!! – fulmicoton
1 upvote
  flag
combine that with Eli's answer, and insert duplicate "_comment" keys all around, then you get the best of both worlds. – Paolo Priotto
upvote
  flag
If you have a parser that errors when a duplicate key is found to prevent data loss by mistake, this would break... It is not a good idea to create comments this way, as they aren't comments and if the parser was using some logic so it wouldn't read top to bottom it would break too. Please don't use this as it is against the spec. – Jose Sutilo
8 upvote
  flag
This answer is cancer. My dev. guys did the same without reading through the comments. Now we are burning ourselves while stream through the content from RPC server. – asyncwait
2 upvote
  flag
"all the implementations handle it the same" - jju has an option to throw on these jsons – alex
29 upvote
  flag
This is the most controversial post on SO. – bjb568
1 upvote
  flag
You could easily state that your "comment" properties either have a single string as their value, or an array of strings. That way you can include as many comment lines as you like, while staying valid JSON. – gnasher729
1 upvote
  flag
I really like the way you think.. Although the specifications state that the key names be unique, it is just a way of saying otherwise the last one overrides every other key – Akshay Khandelwal
upvote
  flag
@AkshayKhandelwal: You apparently failed to comprehend this comment. In a nutshell: There are four different strategies parsers choose when confronted with non-unique names in an object. Besides, the specification makes no guarantees with respect to persisting any ordering, so "last" doesn't make sense anyway. Stop spreading wishful thinking as if it were factually correct. – IInspectable
1 upvote
  flag
You are stepping into the region of implementation dependency. – Derek 朕會功夫
upvote
  flag
Have my upvote for the brazen courage to do this kind of thing. – Renan

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.

To cut a JSON item into parts I add "dummy comment" lines:

{

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

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

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

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

}
13 upvote
  flag
You've emulated an INI file structure in JSON. Please, put down your Golden Hammer. – Artur Czajka
3 upvote
  flag
RFC says "The names within an object SHOULD be unique". Also see this person that is having an error parsing JSON like the above: //allinonescript.com/questions/4912386/… – Full Decent
upvote
  flag
If you're using a schema to validate the JSON, it may fail due to the extra fields. – gregsdennis
1 upvote
  flag
If you're really determined to add comments to your JSON, it would make much more sense to do something like this: { "comment-001":"This is where you do abc...", "comment-002":"This is where you do xyz..." } This keeps the name unique and lets you add whatever string value you like. It's still a kludge, because comments should not be part of your JSON. As another alternative, why not add comments before or after your JSON, but not within it? – Jazimov

Sigh. Why not just add fields, e.g.

{
    "note1" : "This demonstrates the provision of annotations within a JSON file",
    "field1" : 12,
    "field2" : "some text",

    "note2" : "Add more annotations as necessary"
}

Just make sure your "notex" names don't conflict with any real fields.

4 upvote
  flag
Just make sure your "notex" names don't conflict with any real fields. is the problem. This is not an arbitrary solution. – Full Decent
2 upvote
  flag
This also presents the issue that the comments cannot be stripped out by a minification utility before transmission, unavoidably leading to bigger hunks of data being transmitted that serve no purpose on the other end of the transmission. I really feel like taking comment support out of the JSON spec is unfortunate. Specifically because people ARE going to hack solutions together. Taking the support out of the spec is an attempt at behavioral control that is simply going to fail and produce even bigger incompatibilities down the road due to proliferation of mutually-incompatible workarounds. – Craig
1 upvote
  flag
in config files, I use {"/* ---- my section ----*/":0}. This is valid JSON, as JSON accepts any character in the key string. It will not collide with other properties and nobody cares or reordering. Still, 2 comments must not be the same. – olivr
1 upvote
  flag
If you're using a schema to validate the JSON, it may fail due to the extra fields. – gregsdennis
upvote
  flag
Some object unmarshallers (e.g. Jackson, under some configurations) throw exceptions on unknown fields. – slim

The author of JSON wants us to include comments in the JSON, but strip them out before parsing them (see link provided by Michael Burr.) If JSON should have comments, why not standardize them, and let the JSON parser do the job? I don't agree with the logic there, but, alas, that's the standard. Using YAML solution as suggested by others is good, but requires library dependency.

If you want to strip out comments, but don't want to have a library dependency, here is a two-line solution, which works for C++-style comments, but can be adapted to others:

var comments=new RegExp("//.*", 'mg');
data = JSON.parse(fs.readFileSync(sample_file, 'utf8').replace(comments, ''));

Note that this solution can only be used in cases where you can be sure that the JSON data does not contain the comment initiator, e.g. ('//').

Another way to achieve JSON parsing, stripping of comments, and no extra library, is to evaluate the JSON in a JS interpreter. The caveat with that approach, of course, is that you would only want to evaluate untainted data (no untrusted user-input.) Here is an example of this approach in node.js -- another caveat, following example will only read the data once and then it will be cached:

data = require(fs.realpathSync(doctree_fp));
5 upvote
  flag
This does not work, because it doesn't take into account if /* could be escaped, or could be inside a string literal. JSON is not a regular grammar and thus regular expressions are not enough. You have to parse it to find out where the comments are. – Kyle Simpson
upvote
  flag
It will work in limited situations where you can be sure that your JSON does not contain any data with the comment string in it. Thank you for pointing out that limitation. I have edited the post. – Joshua Richardson
upvote
  flag
+1 for the link! Actually I think it is a good thing that comments are not supported because when sending data between a client and server, comments are definitively useless and pump lots of bandwidth for nothing. It's like someone who would ask to have comments in an MP3 structure or a JPEG data block... – Alexis Wilke
upvote
  flag
Thanks for the +1! You have to remember that JSON is used for much more than server/client communication. Also, depending upon your data size, and packet size, sending comments may not increase your bandwidth at all, and it could be useful for your client to have access to the extra context, and you could always have the server strip the comments if you didn't want to send them over the wire. – Joshua Richardson
upvote
  flag
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. – toolbear
upvote
  flag
@AlexisWilke, "comments are definitively useless and pump lots of bandwidth for nothing" -- this is specifically why comments should be supported in the spec. Just look at the number of suggested workarounds that involve numerous different-but-similar ways of schlepping comments into the JSON as data, guaranteeing that a minification tool cannot remove the comments, guaranteeing that they get transmitted over the wire, and forcing the remote parser to deal with them with varying degrees of success. You try to force people ideologically, and they find ways around you. Just the way it is... – Craig
upvote
  flag
@Craig, Why not use C/C++ like comments on your end and use cpp to remove them? (with cpp from gcc you want to use the -P (capital P) to avoid the # <line#> ... entries.) That makes it easy enough, I think. – Alexis Wilke
upvote
  flag
@AlexisWilke that's fine, except it isn't a JSON standard and you can't just presume I'm working on Linux and able to shell out and pipe my files through cpp--I'm not. So I added code to my program to strip out C/C++ comments. My point, really, is that people will find a way to add comments anyway, but they'll now add them as JSON data in a million slightly different formats that no automated tool can detect and remove from the data stream, so the attempt to remove comments will perversely guarantee the existence of comments in the JSON and bulking up data transfers. – Craig
upvote
  flag
@Craig, As a side note, cpp is available under MS-Windows. Although frankly writing your own little tool is probably as easy than messing around with cygwin or MinGW... Now I agree that it is not exactly JSON, but it looks like many interpreters do understand similar extension (C/C++ comments.) – Alexis Wilke
upvote
  flag
@AlexisWilke at some point, though, doesn't all that seem a little bit like going to heroic lengths just to be able to put a comment in your JSON file? In my case, I just need a bit of code (not an entire C/C++ compiler, running wrapped in an extra runtime library, no less if running under Cygwin/Ming), to strip comments out before I can pass my configuration files through the JSON parser. I also detect when the config files change and dynamically reload them, etc. How lame is it that I can't simply put comments in the files and not worry about it? It's super lame. That's how much. ;-) – Craig
upvote
  flag
Your JS interpreter solution is the Nancy Pelosi approach to JSON parsing: you have to pass it to find out what is in it. Of course there may be unintended side effects. – Full Decent
upvote
  flag
Note that the regexp doesn't work with URLs: "url": "http:// ... (oops!). You definitely need a real "JSON+comments" parser to strip comments. – Florian F

There is a good solution (hack), which is valid JSON. Just make the same key twice (or more). For example:

{
  "param" : "This is the comment place",
  "param" : "This is value place",
}

So JSON will understand this as:

{
  "param" : "This is value place",
}
7 upvote
  flag
This method may cause some troubles if anybody will loop through the object. On the first iteration the program will have no information that the entry is a comment. – user2073253
5 upvote
  flag
RFC says: "The names within an object SHOULD be unique". See this error reported at: //allinonescript.com/questions/4912386/… – Full Decent
5 upvote
  flag
Doing this is an invitation for creating JSON that blows up on you at some random point in the future. – toolbear
5 upvote
  flag
There is no guarantee that order matters in the list of object name/value pairs. A parser could parse them "out of order" and then this is broken. – Mark Lakata
2 upvote
  flag
Behaviour of a JSON parser with this kind of code is undefined. There is nothing to say that the parser behaves as if only the last value was present. It could behave as if only the first value was present, or any value, or as if the value was an array. – gnasher729
upvote
  flag
This is terribly bad advice. As others have pointed out before, the behavior is undefined. Different parsers will show different behavior. Some will return the first "param", some will return the second "param", some will stop with an error. It was said before, but this advice is so bad that it's worth repeating that it's bad. – Christian Hujer
upvote
  flag
This might work in a specific implementation but it would be brittle, unless you have control over whatever ingests the json and nothing else is going to use the json data. – ggb667
upvote
  flag
@toolbear JSON does not "blow up". The parser does. It is a doubtful solution. But not worse than adding "_comment". Maybe better than nothing. – Rolf

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 spec does not allow comments.

upvote
  flag
Opening that link timed out when I tried it: The connection to the server was reset while the page was loading. – Peter Mortensen

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.org for JavaScript, Java, Python, PHP, Rust, Go, Ruby and C# libraries.

upvote
  flag
if you look at the spec you'd see that it's a superset of json. you can convert from/to json. – laktak
11 upvote
  flag
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
4 upvote
  flag
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.p‌​df 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
14 upvote
  flag
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: //allinonescript.com/questions/450399/…) or stick with curmudgeony, yet unambiguous JSON. – toolbear
1 upvote
  flag
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
8 upvote
  flag
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

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;
1 upvote
  flag
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. – Full Decent
upvote
  flag
Yes. This is an abuse of the RFC not envisioned by its author. You can accept that without flagging and modding my comments/answer to oblivion. – Full Decent

I just found "grunt-strip-json-comments".

“Strip comments from JSON. It lets you use comments in your JSON files!”

{
    // Rainbows
    "unicorn": /* ❤ */ "cake"
}
upvote
  flag
Might as well minify that JSON while you're at it. See @kyle-simpson's answer about JSON.minify. – toolbear

Yes, you can, but your parse will probably fail (there is no standard).

To parse it you should remove those comments, or by hand, or using a regular expression:

It replaces any comments, like:

/****
 * Hey
 */

/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/

It replaces any comments, like:

// Hey

/\/\/.*/

In JavaScript, you could do something like this:

jsonString = jsonString.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/, "").replace(/\/\/.*/,"")
var object = JSON.parse(jsonString);
2 upvote
  flag
Your regexp would remove things like /*hey*/ even from inside strings. – 6502
upvote
  flag
Good catch! So just change some stuff on regex. – Maurício Giordano
1 upvote
  flag
Regular expressions for structured languages are notoriously hard to get right. Check out @kyle-simpson's answer about JSON.minify as an alternative to ad hoc regexps. – toolbear

If your context is Node.js configuration, you might consider JavaScript via module.exports as an alternative to JSON:

module.exports = {
    "key": "value",

    // And with comments!
    "key2": "value2"
};

The require syntax will still be the same. Being JavaScript, the file extension should be .js.

upvote
  flag
I really thought there was no point going on to the second page of answers for this question but this is EXACTLY what I was looking for and works flawlessly! thanks. – rob

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.

upvote
  flag
It is hard to understand why someone would have problem with stating a fact. – dvdmn
upvote
  flag
I would assume someone took exception because the above is no longer JSON, or is invalid JSON. Perhaps adding a short disclaimer would appease. – toolbear
3 upvote
  flag
I completely agree with you, and yet there are 883 upvotes so far for the non-answer that just states the obvious. Ideological purity valued above helpful information, that's SO for you. – John

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'}

There are other libraries that are json compatible, which support comments. One notable example is the "Hashcorp Language" (HCL)". Written by the same people who made Vagrant, packer, consul, and vault.

https://github.com/hashicorp/hcl

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.

As many answers have already pointed out, JSON does not natively have comments. Of course sometimes you want them anyway. For Python, two ways to do that are with commentjson (# and // for Python 2 only) or json_tricks (# or // for Python 2 and Python 3), which has several other features. Disclaimer: I made json_tricks.

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.

1 upvote
  flag
Could you please add an example? Then you may actually need those extra characters. – dgilperez
3 upvote
  flag
It's required by the SO guidelines to provide an actual answer. Link-only answers are not desired. You can check the guidelines //allinonescript.com/help/how-to-answer – dgilperez
1 upvote
  flag
SO is moderated by its users. That means I can provide an answer if I have it the same way I can comment yours if it doesn't follow guidelines. That's how SO gets to be a great resource. – dgilperez

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.

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.

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 it harder to parse, not easier. 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.

3 upvote
  flag
Parsing out comments is easy. Leaving comments out of the JSON spec is ridiculous. It isn't always (or even often) about the need for annotations and has nothing to do with whether it is or isn't a markup language. People will put comments in anyway, using various and sundry specs because there is no standard, leading to a confusion of formats down the road, and sometimes (often) it's just about working with test data or configuration files and needing to comment something out to test a change, without losing the original values by deleting them. – Craig
upvote
  flag
adding comments to JSON is thoughtcrime ... JSOC has been notified ... remain at your screen ... – Dominic Cerisano
upvote
  flag
What if you simply want to comment some fields out of a json file? – GreenAsJade
upvote
  flag
Since json is designed for code generators, manual editing is not really a use-case (out of bounds, sir). – Dominic Cerisano

You can use JSON with comments in it, if you load it as a text file, and then remove comments from it.

You can use decomment library for that. Below is a complete example.

Input JSON (file input.js):

/*
* multi-line comments
**/
{
    "value": 123 // one-line comment
}

Test Application:

var decomment = require('decomment');
var fs = require('fs');

fs.readFile('input.js', 'utf8', function (err, data) {
    if (err) {
        console.log(err);
    } else {
        var text = decomment(data); // removing comments
        var json = JSON.parse(text); // parsing JSON
        console.log(json);
    }
});

Output:

{ value: 123 }

See also: gulp-decomment, grunt-decomment

You can use JSON-LD and the schema.org comment type to properly write comments:

{
    "https://schema.org/comment": "this is a comment"
}

If you are using PHP, you can use this function to search for and remove // /* type comments from the JSON string before parsing it into an object/array:

function json_clean_decode($json, $assoc = true, $depth = 512, $options = 0) {
       // search and remove comments like /* */ and //
       $json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $json);

       if(version_compare(phpversion(), '5.4.0', '>=')) {
           $json = json_decode($json, $assoc, $depth, $options);
       }
       elseif(version_compare(phpversion(), '5.3.0', '>=')) {
           $json = json_decode($json, $assoc, $depth);
       }
       else {
           $json = json_decode($json, $assoc);
       }

       return $json;
   }

Hope this helps!

upvote
  flag
solution category == 'transform through preproc' – dreftymac

In my case, I need use comments to debug purposes, prior the output of the JSON structure. So I decided to use debug info in the http header, to avoid breaking the client:

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

enter image description here

Yes, you can have comments. But I will not recommend whatever reason mentioned above. I did some investigation, I found all JSON require method uses JSON.parse method. So I come solution, we can override or do monkey patching around JSON.parse.

Note: tested on nodejs only ;-)

var oldParse = JSON.parse;
JSON.parse = parse;
function parse(json){
    json = json.replace(/\/\*.+\*\//,function(comment){
        console.log("comment:", comment);
        return "";
    });
    return oldParse(json)
}

JSON file:

{
  "test":1
  /*hello babe*/
}
1 upvote
  flag
{ what_if: "I happen to have /* slashes and asterisks */ in my data?" } – DSimon
upvote
  flag
Will work, tested on browser – xdeepakv
upvote
  flag
What I mean is, is most languages you don't have to worry about comment sequences inside strings. Even in a JSON implementation that supported comments, I would expect parsing my example to result in an object with the key "what_if" and the value "I happen to have /* slashes and asterisks */ in my data?", not "I happen to have in my data". – DSimon
upvote
  flag
Using regex you can avoid data conversion to. What I understand, this should not be the case. JSON is used as a data not the language. So avoid garbage data or comments in data. :-D Most of the language, you write code that compiles in some other format. Here in JS, it is dynamically bind. There is no such type of compilation happens. V8 do some optimization, but that is also in push and failure method. – xdeepakv

You can use simple preprocessing via regular expression. For instance, the following function will decode commented json in PHP:

function json_decode_commented ($data, $objectsAsArrays = false, $maxDepth = 512, $opts) {
  $data = preg_replace('~
    (" (?:[^"\\\\] | \\\\\\\\ | \\\\")*+ ") | \# [^\v]*+ | // [^\v]*+ | /\* .*? \*/
  ~xs', '$1', $data);

  return json_decode($data, $objectsAsArrays, $maxDepth, $opts);
}

It supports all PHP-style comments: /*, #, //. String literals are preserved as is.

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"
}
upvote
  flag
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
upvote
  flag
This method breaks some libraries, which require that the key must be unique. I'm working around that issue by numbering the comments. – MovGP0
upvote
  flag
good comment, I found this question on SO ... this part seems not to be covered by the spec //allinonescript.com/questions/21832701/… – mana
upvote
  flag
I guess //1 //2 //3 would work. – ggb667

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