8287

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

Steve Chambers
  • 31,993
  • 15
  • 129
  • 173
Michael Gundlach
  • 94,522
  • 11
  • 34
  • 39
  • 179
    @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 Oct 28 '08 at 20:51
  • 29
    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. – driftcatcher Feb 01 '13 at 15:12
  • 14
    and perhaps this is one reason why TOML was created.. – Alex Nolasco May 01 '13 at 05:22
  • 14
    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 Sep 25 '13 at 11:29
  • 1
    Check out http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=? and you will see comments. This is JSONP, though, not pure JSON. See my response below. – Sergey Orshanskiy Oct 07 '13 at 20:39
  • 19
    JSON5 supports comments: http://stackoverflow.com/a/7901053/108238 – schoetbi Feb 02 '15 at 11:13
  • 2
    Ruby's json parser is another example of a parser that supports comments. – Ben Crowell Jun 20 '16 at 17:21
  • 3
    If you want a language for configuration with comments see [TOML](https://github.com/toml-lang/toml) – schoetbi Sep 12 '16 at 13:20
  • 2
    Comments are not permitted because it's too late to support comments. Major oversight. Ironically, YAML supports comments. – bvj Aug 02 '17 at 07:08
  • 1
    https://www.oreilly.com/learning/adding-comments-in-json has 2 ways to do add a comment functionality to your JSON file – Flotolk Jan 08 '18 at 19:32
  • 1
    here is a nice trick https://gist.github.com/MoOx/5271067 – osama yaccoub Apr 04 '18 at 15:48
  • 4
    This is why YAML is superior. – Chloe Jul 17 '18 at 17:07
  • 1
    Look up RFC 4627 and related. – MikeW Oct 29 '18 at 10:29
  • 4
    One of the key goals of JSON is to eliminate the boiler plate of formats like XML. It's all about the data and minimum markup. It's an opinionated format explicitly preventing you from using comments. json-schema will help somewhat in helping people understand the data, in a similar manner to XML schemas, but tool support needs to improve. JSON has crept into other areas than for transfer across the internet now, and I do agree that it would be handy with comments for that use. – hktegner Mar 31 '19 at 11:08
  • 1
    `jsonc` files should work, hence the definition: **JSON** with **C**omments. – mekb Jul 21 '19 at 03:19
  • 5
    "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 – Dominic Cerisano Nov 20 '19 at 15:45
  • 1
    if a .json file cannot support comments, perhaps there should be a parallel file with an extension (such as .jsondoc) to contain data descriptions/comments for the .json file of the same name. – RufusVS Feb 12 '20 at 17:28
  • 1
    Officially, JSON standard doesn't support comments. In practice, most actual implementations do support comments (but in some this needs to be explicitly enabled). So: if you control the application which reads your JSON file, and only use it within that application, and the file is meant to be human-readable, and your JSON library supports them, then by all means use comments. If the file is meant to be sent to another application, e.g. over the web, and especially if it is meant to be machine-written and machine-read, then don't use comments (they are non-portable and serve no purpose). – Mike Rosoft Mar 03 '20 at 11:08
  • 3
    @schoetbi, JSON5 is unofficial. It is not "the 5th version of JSON", despite what its creators would have you believe. See https://github.com/json5/json5-spec/issues/15 – HullCityFan852 Apr 20 '20 at 00:51
  • 2
    To add to @HullCityFan852's comment: `JSON` is widely supported by multiple standards organizations, as can be seen in its wikipedia article. `JSON5` is one of many non-standard parsers; the `5` appears to be an attempt to capitalize on the popularity of `HTML5`. IMHO, despite the possibly laudable goals of the author(s), this is a misleading name, so not acceptable. – ToolmakerSteve Apr 30 '20 at 23:40
  • 1
    As a responsible dev, the question you should be asking yourself is *"Just because I can, do I really need to **hack** this solution?"* JSON is quite an old language-agnostic data interchange format. If there really was a need for "comments" then a specification change would have already been made. This need for comment arise when devs want to do things like use JSON to represent configuration of the app or something similar. At that point should you really be using JSON to do that job? – nabster May 19 '20 at 16:16
  • 1
    [manifest.json](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) supports `// comments`. Just in case someone comes here for this special case, like I did it before. – stackprotector Sep 17 '20 at 06:48
  • 1
    YAML might be more appropriate if the data need to be human readable. – Mudream Sep 23 '20 at 10:41
  • 1
    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 Nov 20 '20 at 20:44
  • 1
    Android's JSONObject support C-style comments in its parser. – Pointer Null Jan 08 '21 at 10:38

56 Answers56

6147

No.

The JSON is data only, and if you include a comment, then it will 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"
            }
         }
      }
   }
}
EnzoR
  • 2,523
  • 2
  • 16
  • 19
Eli
  • 88,788
  • 20
  • 72
  • 81
  • 265
    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 Feb 03 '10 at 11:41
  • 29
    BTW, the json library for Java [google-gson](http://code.google.com/p/google-gson/) has support for comments. – centic Oct 01 '12 at 12:21
  • 12
    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 Aug 11 '14 at 12:58
  • @JuanMendes: you are allowed to have the same key multiple times. – mike3996 Dec 17 '14 at 07:03
  • 1
    We can to select more unique comment keys format for this. Something like `{"": "Comment text"}` looks ok. `"/* glossary */"` too. – vp_arth Dec 19 '14 at 04:21
  • 1
    Why is `GlossList` not an array (`GlossList: [ { .. }, { .. } ]`)? – Luca Steeb May 12 '15 at 12:58
  • 1
    If you're using a schema to validate the JSON, it may fail due to the extra fields. – gregsdennis Jun 26 '15 at 00:31
  • 52
    you could also use "//": this looks more native and is still repeatable in the same parent – smnbbrv Aug 28 '15 at 09:59
  • 1
    @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", "line 2", "line 3" ]`. – TripeHound Oct 09 '15 at 14:11
  • 1
    The thing is it changes the semantic of the JSON, e.g. changing the length of an array. – Qian Chen Dec 21 '15 at 12:21
  • 13
    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. – Петър Петров Feb 27 '16 at 13:59
  • There is [JSON5](http://stackoverflow.com/questions/244777/can-comments-be-used-in-json/33885543#33885543) (`5` referring to [ECMAScript 5](https://en.wikipedia.org/wiki/ECMAScript#5th_Edition) (and later)). – Peter Mortensen Jan 19 '17 at 18:42
  • 1
    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 Aug 14 '17 at 18:48
  • 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 Sep 07 '17 at 17:41
  • Yea you can try to use `{"//": "Your comment"}` – danger89 Mar 20 '18 at 19:12
  • But be careful! Some fully parsing engines need something as @JsonIgnoreProperties annotation, or else they will see unknown field as an error. – Gangnus May 15 '18 at 05:08
  • Just capturing a relevant excerpt from the first link that @MichaelBurr provided (the second is seemingly irretrievable): "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 – chb Sep 17 '18 at 00:45
  • 2
    One of the links in my June 2012 comment no longer works. Another reader (@douglasgross) has provided this current link: https://groups.yahoo.com/neo/groups/json/conversations/topics/156 – Michael Burr Sep 27 '18 at 22:20
  • @danger89 you could, but this changes the length of the array. However, I see do see this used in tutorials where the code isn't going to be used in production – Pranav A. Nov 24 '18 at 22:44
  • `_comment` is also the official workaround within composer.json as committed by composer author Seldaek in [98b0af1](https://github.com/composer/composer/commit/98b0af1386f7ff730c3330e2525c1d66998c7f90) – noobish Feb 02 '19 at 00:12
  • 2
    @RobFonseca-Ensor but what if we will have a field called `__comment`? We would need to have a new field `___comment`. – null Mar 08 '19 at 17:27
  • 1
    Agh! ... Whoever designed the spec did they never imagine it ever being used for configurations files where comments come in really really handy. Some things like Microsoft.Extensions.Configuration.Json manage seem to ride out //blah comments, whereas others like powershell ConvertFrom-Json do not. So be careful with adding comments. – andrew pate Sep 25 '19 at 13:35
  • Unfortunately my babel is bitching `Error: Unknown option: _comment.` – Thielicious Jun 24 '20 at 22:31
1962

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)
Federico Navarrete
  • 2,211
  • 4
  • 32
  • 53
stakx - no longer contributing
  • 77,057
  • 17
  • 151
  • 248
  • 80
    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 Aug 07 '14 at 19:26
  • 30
    @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 - no longer contributing Sep 28 '15 at 07:01
  • 9
    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 Oct 31 '17 at 17:36
  • 76
    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 Jan 21 '18 at 00:29
  • 22
    @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 - no longer contributing Jan 21 '18 at 07:48
  • 6
    @stakx, I disagree. That's like saying "Cars didn't start out with seatbelts so we shouldn't have added them. If you want a seatbelt, you're using the car wrong". If adding comments to JSON would make it more useful (which it certainly would), we should just add them. Instead of accepting that JSON just "is what it is", let's make it what it should be. – d512 Jun 18 '19 at 20:29
  • 1
    @d512: If you feel strongly about what the JSON format *should be* (vs. what it *is* today), perhaps take this up with the IETF to have the JSON format specification [RFC 8259](https://tools.ietf.org/html/rfc8259) changed. – stakx - no longer contributing Jul 02 '19 at 16:00
  • 1
    @d512 to stick with your example: JSON is a bike, and other formats that allow comments are cars. You could add a seatbelt to a bike (or comments to JSON), but that's not the intended use. Besides, you can just add a `_comment` field as specified in the accepted answer. – PixelMaster Jul 10 '19 at 14:38
  • 2
    @PixelMaster then it's time to upgrade JSON to car status. Nobody would except having to declare a string variable called `_comment` in their code so let's not resort to those types of hacks in JSON. – d512 Jul 10 '19 at 18:33
  • 1
    @d512 you don't craft a car out of a bike, though - you get an entirely different vehicle, a new car (^= data format), instead. Simultaneously, the existence of cars doesn't render bikes obsolete. – PixelMaster Jul 10 '19 at 19:51
  • 1
    @PixelMaster So move the entire industry to a new data format that supports comments rather than just adding them to JSON? We don't need to a whole giant overhaul of the format. It's not analogous to turning a bike into a car. We just need to one, common place, common sense feature. – d512 Jul 24 '19 at 18:58
891

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.

Kyle Simpson
  • 13,954
  • 2
  • 28
  • 47
  • 167
    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: https://gist.github.com/1170297 . On some large test files your implementation takes 74 seconds and mine 0.06 seconds. – WizKid Aug 25 '11 at 09:16
  • 62
    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: https://github.com/getify/json.minify – Kyle Simpson Aug 30 '11 at 17:20
  • 3
    Perl's JSON supports # comments. – Johannes Ernst Nov 14 '11 at 17:36
  • 2
    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 Dec 15 '11 at 15:34
  • @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 Mar 07 '12 at 00:07
  • 2
    You might find it interesting to hear, from the author of JSON, why comments were left out of the spec: http://youtu.be/-C-JoyNuQJs?t=48m53s – MiniGod Jan 31 '13 at 03:29
  • 16
    @MiniGod I have already heard Doug's thoughts on this topic many times. I addressed them long ago in my blog post: http://blog.getify.com/json-comments/ – Kyle Simpson Feb 26 '13 at 23:21
  • 22
    @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 Mar 28 '14 at 22:09
  • 2
    @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 Apr 01 '14 at 16:38
  • @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 Apr 09 '14 at 03:14
  • @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 Apr 09 '14 at 03:16
  • 3
    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 Apr 09 '14 at 19:41
  • @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 May 15 '14 at 05:50
  • 4
    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: foo12345 – ManicDee Jun 16 '14 at 05:28
  • @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 Jul 09 '14 at 15:38
  • 2
    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 Sep 10 '14 at 16:45
  • 22
    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 Jan 27 '16 at 19:31
  • @KyleSimpson **404 on your blog link**, update the link if you a new copy – Srinath Ganesh May 24 '16 at 11:42
  • 2
    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. – Remember Monica May 01 '17 at 16:22
  • 4
    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 May 30 '17 at 17:56
  • 12
    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 Nov 12 '18 at 20:20
490

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+

Community
  • 1
  • 1
Artur Czajka
  • 16,393
  • 2
  • 25
  • 29
  • 247
    I thought JSON was to supposed to be more human readable than, say, XML? Comments are for readability. – intrepidis Oct 14 '12 at 13:00
  • 32
    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 Oct 14 '12 at 13:04
  • 2
    Removing `/* */` comments also made JSON a better subset of YAML. – Schwern Nov 29 '12 at 07:47
  • 2
    @Schwern But YAML does allow `#` comments, so your point is kind of muoot – Juan Mendes Apr 04 '13 at 17:50
  • 1
    @JuanMendes I don't understand why that makes my point about JSON/YAML compatibility moot. What do you think my point was? – Schwern Apr 04 '13 at 18:28
  • @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 Apr 04 '13 at 23:22
  • 4
    @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 Apr 05 '13 at 02:26
  • 9
    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 May 16 '13 at 22:16
  • @ChrisNash It was not meant to be more readable than XML, just easily readable by humans. http://www.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 Aug 02 '13 at 18:18
  • 87
    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 Sep 23 '13 at 02:28
  • 1
    @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 Sep 24 '13 at 12:22
  • 18
    @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 Oct 04 '13 at 02:42
  • 16
    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 May 29 '14 at 17:52
  • 32
    "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 Jun 12 '14 at 14:22
  • 1
    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 Aug 07 '14 at 19:24
  • 16
    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 Sep 15 '14 at 06:48
  • 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 Sep 15 '14 at 06:54
  • 5
    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 Jan 29 '15 at 09:55
  • 95
    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 May 14 '15 at 17:24
  • 1
    @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 Aug 11 '17 at 12:37
  • 1
    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 Aug 31 '17 at 13:27
  • 3
    Removing comments is a 'BAD IDEA'. As the comment is also data for the person reading it,removing them because they are not data is a bad argument. In addition, it can be argued that all comments in any language, specification file, config file, etc are data. Just because it is not intended for the machine it does not mean it's not data. – Mac Aug 24 '18 at 15:41
  • I'm assuming that `JSMin` refers to the JavaScript minifier on Crockford's site at https://www.crockford.com/jsmin.html , is that correct? – cowlinator Nov 19 '19 at 21:02
285

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.

laktak
  • 47,916
  • 15
  • 112
  • 150
  • if you look at the spec you'd see that it's a superset of json. you can convert from/to json. – laktak Jun 12 '14 at 14:53
  • 23
    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 Jun 30 '14 at 19:20
  • 11
    Sorry about that, @konsolebox. Perhaps you might reconsider your "well-defined JSON is your opinion" view after reading http://www.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 Jul 09 '14 at 16:02
  • 25
    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: http://stackoverflow.com/questions/450399/which-java-yaml-library-should-i-use/1863814#comment6582202_1863814) or stick with curmudgeony, yet unambiguous JSON. – toolbear Aug 07 '14 at 18:25
  • 5
    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 Feb 10 '15 at 15:15
  • 20
    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 Apr 06 '16 at 14:20
  • 1
    "*It was also never intended to be used for configuration files where comments would be needed.*" But JSON is used for JSON schemas, where comments are extremely helpful. Comments can be included in *description* elements, but that turns comments into data. They're also helpful for documentation, where it would be great to be able to validate the JSON without having to first remove the comments. – RobG Jan 03 '19 at 00:32
  • Tell that to the [Jest](https://en.wikipedia.org/wiki/Jest_(JavaScript_framework)) developers (e.g., configuration file `package.json`). – Peter Mortensen Oct 08 '20 at 17:17
223

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!

thanksd
  • 44,567
  • 20
  • 126
  • 130
p3drosola
  • 5,462
  • 2
  • 20
  • 30
  • 167
    From [the specification](http://www.ietf.org/rfc/rfc4627.txt): The names within an object SHOULD be unique. – Quentin Aug 02 '13 at 13:50
  • 2
    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. – p3drosola Aug 02 '13 at 13:57
  • 128
    "all the implementations handle it the same" — That's a difficult thing to prove. – Quentin Aug 02 '13 at 14:20
  • 100
    The order of elements in JSON is not guaranteed. That means the "last" item could change! – sep332 Aug 02 '13 at 14:33
  • 3
    @sep332 they are in the case of a hand edited json/config file. – Tracker1 Aug 02 '13 at 14:36
  • 11
    @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 Aug 02 '13 at 14:37
  • 6
    @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 Aug 02 '13 at 14:39
  • 68
    This clearly violates the spec (see above comments), don't do this. https://www.ietf.org/rfc/rfc4627.txt?number=4627 – voidlogic Aug 02 '13 at 14:39
  • 2
    @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 Aug 02 '13 at 14:39
  • 7
    It would be totally reasonable for a parser to discard values of existing keys instead of overwriting them. – Gipsy King Aug 02 '13 at 14:44
  • 5
    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 Aug 02 '13 at 14:44
  • 10
    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 Aug 02 '13 at 14:47
  • 5
    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 Aug 02 '13 at 14:53
  • 356
    __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 Aug 02 '13 at 14:55
  • 2
    @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 Aug 02 '13 at 14:58
  • 17
    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 Aug 02 '13 at 16:04
  • 11
    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 Aug 02 '13 at 16:19
  • 10
    That is wrong on so many levels I don't even know where to begin. I'll just put that here - http://pragprog.com/the-pragmatic-programmer/extracts/coincidence - and try to forget what I just saw. – Geoffrey Bachelet Aug 02 '13 at 18:13
  • 3
    See this question for error case: http://stackoverflow.com/questions/4912386/resolve-jsonexception-duplicate-keys – Paul Tyng Aug 02 '13 at 18:33
  • 3
    Bad idea - leads to confusion, against spec, not future proof and JSLint disqualifies the JSON. – Praveen Vijayan Aug 03 '13 at 05:37
  • 2
    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 Aug 03 '13 at 06:13
  • 1
    ... 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 Aug 03 '13 at 06:21
  • 27
    As we've been working on RFC 4627bis at the IETF in the JSON working group (join us and help! http://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 Aug 03 '13 at 22:03
  • 3
    Bad hack. It's JSON parser matter. At least IAM policy file (AWS) doesn't accept duplicate JSON key. http://www.microsofttranslator.com/bv.aspx?from=&to=en&a=http://dev.classmethod.jp/etc/adding-comment-to-json/ – kyanny Aug 04 '13 at 03:06
  • 11
    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 Aug 04 '13 at 17:28
  • Solr uses multiple Keys. This is incompatible with the major opensource search server!!! – fulmicoton Aug 04 '13 at 22:57
  • 1
    combine that with [Eli's answer](http://stackoverflow.com/a/244858/1317451), and insert duplicate `"_comment"` keys all around, then you get the best of both worlds. – depoulo Aug 05 '13 at 07:47
  • 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 Aug 05 '13 at 11:43
  • 8
    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 Nov 01 '13 at 10:13
  • 2
    "all the implementations handle it the same" - [jju](https://github.com/rlidwka/jju) has an option to throw on these jsons – alex Jan 04 '14 at 00:26
  • 34
    This is the [**most controversial**](http://data.stackexchange.com/stackoverflow/query/466/most-controversial-posts-on-the-site) post on SO. – bjb568 Apr 11 '14 at 18:45
  • 1
    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 Oct 16 '14 at 11:48
  • 2
    You are stepping into the region of implementation dependency. – Derek 朕會功夫 Aug 17 '17 at 20:47
  • The `jsondecode` parser of matlab will create `api_host` and `api_host_1` fields, etc .. – user3240484 Oct 29 '18 at 11:57
154

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

Marnen Laibow-Koser
  • 5,182
  • 1
  • 23
  • 30
  • 1
    Note that the converse is not true (valid YAML !=> valid JSON) – g33kz0r Sep 11 '12 at 04:01
  • 13
    @g33kz0r Correct, hence my description of YAML as a near-superset of JSON. – Marnen Laibow-Koser Sep 12 '12 at 14:58
  • 14
    @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 Mar 28 '14 at 12:57
  • 7
    Downside: `yaml` library isn't shipped with Python. – Bleeding Fingers Apr 15 '14 at 10:06
  • 1
    @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 Aug 13 '14 at 19:25
  • 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. – toolbear Aug 17 '14 at 23:32
  • 2
    @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 Aug 18 '14 at 20:38
  • 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. – toolbear Aug 25 '14 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. – toolbear Aug 25 '14 at 11:56
  • 3
    @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 Sep 13 '14 at 00:58
  • 2
    yaml >> json . And python has a good yaml library. I have to roll my own in Scala - but still worth it. – StephenBoesch Oct 02 '16 at 05:35
  • 2
    This answer is valid in accomplishing adding comments to json. It is no longer standard json. But it is still json. Comments + Json + Yaml Loader = valid solution. Some frameworks/languages require install json. It coming installed by default is a poor excuse not to use yaml. But loading time and library size are valid reasons to avoid it. May fit or may not. Valid answer. – TamusJRoyce Dec 26 '18 at 17:22
  • 1
    @TamusJRoyce I wouldn’t call that a valid solution, really. If you’re going to use a YAML loader, then go all in and use YAML. If you really have to use JSON (which is a terrible file format anyway), stick to the standard and don’t use comments. – Marnen Laibow-Koser Dec 27 '18 at 21:58
  • 1
    something that works is a valid solution. Even if not optimal. Maybe you are developing and temporarily need comments. Then refactor it out. – TamusJRoyce Dec 27 '18 at 22:44
  • 1
    At one time, I built a config file parser using yaml. It was able to consume .ini, xml, yaml, and json. And spit out pure json. If your use is to process something ugly into something pure, there is nothing wrong with using a heavy library like yaml. yaml is anything but hackish or aweful. Treat it as an ETL or repair json tool. Super helpful and useful. Or even a build tool that strips comments. Webpack comes to mind. – TamusJRoyce Feb 14 '19 at 00:58
  • 1
    @TamusJRoyce Yes, I love YAML. What I was objecting to as hackish was parsing JSON+comments as if it were YAML, rather than going all in with either standard YAML or standard JSON. – Marnen Laibow-Koser Feb 14 '19 at 01:00
122

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Cheery
  • 21,751
  • 13
  • 55
  • 80
93

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.

t-b
  • 63
  • 1
  • 6
schoetbi
  • 9,843
  • 7
  • 44
  • 70
  • Groovy has some [built-in classes for handling JSON](http://www.groovy-lang.org/json.html). 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 Nov 06 '15 at 21:47
  • Newtonsoft Json.NET also support C-style comments with no problems – Max Apr 17 '20 at 01:19
77

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
raffel
  • 1,181
  • 9
  • 8
  • 6
    Is JSON schema alive? It exists but is it supported by any known library? – Munhitsu Oct 29 '12 at 14:31
  • 1
    yes, the [json-schema google group](https://groups.google.com/forum/#!forum/json-schema) is fairly active and I would recommend [JSV](https://github.com/garycourt/JSV) for a good JavaScript implementation of a JSON Schema validator. – raffel Nov 27 '12 at 11:34
  • 5
    This only helps with structured documentation, not ad-hoc documentation – Juan Mendes Apr 04 '13 at 17:47
  • If you use clojure (and I'm sure you don't) there's a reasonably featured open-source JSON schema parser here: https://github.com/bigmlcom/closchema – charleslparker Apr 15 '13 at 13:50
  • @Munhitsu Manatee.Json (.Net) extensively supports JSON schema. – gregsdennis Jun 26 '15 at 00: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 Dec 08 '17 at 11:22
  • Perhaps time for an update? E.g. how widely it is adopted, etc. – Peter Mortensen Oct 08 '20 at 16:34
74

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Andrejs
  • 24,146
  • 10
  • 98
  • 92
63

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"
}
np_6
  • 506
  • 6
  • 17
mana
  • 5,571
  • 5
  • 43
  • 66
  • 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 Nov 01 '17 at 20:44
  • 6
    This method breaks some libraries, which require that the key must be unique. I'm working around that issue by numbering the comments. – MovGP0 Jan 19 '18 at 11:45
  • good comment, I found this question on SO ... this part seems not to be covered by the spec https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object – mana Jan 20 '18 at 19:36
  • 6
    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 Mar 09 '18 at 16:29
59

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 make 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

Dominic Cerisano
  • 2,789
  • 25
  • 41
45

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.

Randika Vishman
  • 7,157
  • 3
  • 55
  • 75
  • 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 Feb 25 '11 at 11:04
  • I agree and have written a JSON parser in Java, available at www.SoftwareMonkey.org, that does exactly that. – Lawrence Dol Jul 28 '12 at 01: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 Jul 27 '13 at 12:09
  • 28
    "...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 Dec 08 '13 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. – toolbear Aug 07 '14 at 19:32
  • One liner JS-compatible regex: `myJson.replace(/("\/\/.*"|"\/\*(?:.|\n)*?")|(\/\/.*|\/\*(?:.|\n)*?\*\/)/g, "$1")` https://regexr.com/3p39p – Maxim Paperno May 08 '18 at 04:34
  • @MaximPaperno Nope, no good: https://regexr.com/5fvda – JLRishe Nov 10 '20 at 17:48
44

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.

Community
  • 1
  • 1
dvdmn
  • 5,659
  • 6
  • 39
  • 51
  • It is hard to understand why someone would have problem with stating a fact. – dvdmn Jul 29 '14 at 14:17
  • 1
    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 Aug 07 '14 at 18:12
  • 5
    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 Aug 20 '14 at 16:48
  • 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 Jun 06 '19 at 03:35
37

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Neil Albrock
  • 965
  • 9
  • 16
  • 23
    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 Sep 01 '09 at 18:20
  • 5
    @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 Dec 11 '10 at 09:03
  • 7
    Metadata belongs in metadata constructs (e.g. HTML tags), not comments. Abusing comments for metadata is just a hack used where no true metadata construct exists. – Marnen Laibow-Koser Sep 06 '11 at 04:55
  • 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 Jun 25 '13 at 14:50
  • 2
    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 Aug 07 '14 at 19:35
35

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.

gaborous
  • 12,649
  • 7
  • 73
  • 94
  • 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. – toolbear Aug 07 '14 at 19:14
33

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
peterk
  • 4,486
  • 4
  • 28
  • 38
  • 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. – Marnen Laibow-Koser Oct 19 '11 at 21:35
  • 2
    how many languages do you think supports YAML out of the box compared to json ? – mmm Jan 13 '12 at 13:26
  • @Hamidam Over a dozen languages support yaml: http://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 Mar 21 '12 at 15:53
  • 5
    YAML interop is a lie: http://stackoverflow.com/questions/450399/which-java-yaml-library-should-i-use/1863814#comment6582202_1863814 . If your instinct is to use JSON for configuration files, follow it. – toolbear Aug 07 '14 at 19:10
  • 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 Dec 02 '15 at 18:24
32

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

See another Stack Overflow question.

Community
  • 1
  • 1
AZ.
  • 6,663
  • 6
  • 38
  • 61
  • And I believe that is why I see a comment in a screenshot on this ASP.NET vNext preview page (under package.json): http://blogs.msdn.com/b/webdev/archive/2014/06/03/asp-net-vnext-in-visual-studio-14-ctp.aspx although I haven't found anything in the spec yet. – webXL Sep 17 '14 at 21:54
31

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!

Basel Shishani
  • 6,625
  • 5
  • 42
  • 62
  • 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 Aug 07 '14 at 19:19
31

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Smit Johnth
  • 1,353
  • 1
  • 14
  • 13
  • 5
    Could you please add an example? Then you may actually need those extra characters. – dgilperez Dec 17 '15 at 00:15
  • 6
    It's required by the SO guidelines to provide an actual answer. Link-only answers are not desired. You can check the guidelines http://stackoverflow.com/help/how-to-answer – dgilperez Dec 29 '15 at 20:06
  • 2
    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 Dec 30 '15 at 11:21
25

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
David
  • 1,873
  • 2
  • 23
  • 37
  • 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. – toolbear Aug 07 '14 at 19:31
  • 2
    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 Aug 07 '14 at 23:37
  • 1
    It's bad voodoo to serve up commented, and thus invalid JSON, which `dojo.xhrGet()` implicitly encourages by accepting. – toolbear Aug 08 '14 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. – Craig Sep 15 '14 at 07:03
23

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Manish Shrivastava
  • 26,075
  • 13
  • 88
  • 100
21

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Sergey Orshanskiy
  • 6,076
  • 41
  • 48
21

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Roy Prins
  • 2,199
  • 1
  • 22
  • 38
20

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;
William Entriken
  • 30,701
  • 17
  • 128
  • 168
  • 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. – William Entriken Sep 24 '14 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? – Claire Nielsen Sep 26 '18 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 Sep 23 '19 at 18:04
  • 1
    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. – William Entriken Sep 26 '19 at 20:22
19

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

WilliamK
  • 1,403
  • 13
  • 10
17

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."
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
fyngyrz
  • 1,878
  • 2
  • 27
  • 39
  • The "reasoning" link is broken. Any chance of finding a current link to it? – Don Hatch Apr 23 '19 at 17:05
  • Don, unfortunately, Google has killed the social media system that contained the post; I have no idea where the original poster went from there, if anywhere. I'll kill the link in the above info, though, so as to remove the ambiguity. Thanks. – fyngyrz Apr 24 '19 at 13:50
  • 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*. – Dominic Cerisano Jul 14 '19 at 16:30
  • 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 Jan 28 '20 at 14:41
16

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.

Audrius Meskauskas
  • 18,378
  • 9
  • 63
  • 78
  • 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? – Xavi Montero Mar 28 '21 at 13:53
  • If you create your own standard, you are the only in the world using it. Something like JSON5 is probably better. – Audrius Meskauskas Mar 28 '21 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. – Xavi Montero Mar 29 '21 at 19:00
14

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

{

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

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

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

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

}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Chris
  • 925
  • 1
  • 11
  • 16
  • 15
    You've emulated an INI file structure in JSON. Please, put down your Golden Hammer. – Artur Czajka Nov 18 '13 at 16:53
  • 4
    RFC says "The names within an object SHOULD be unique". Also see this person that is having an error parsing JSON like the above: https://stackoverflow.com/questions/4912386/resolve-jsonexception-duplicate-keys?lq=1 – William Entriken Jun 10 '14 at 15:58
  • If you're using a schema to validate the JSON, it may fail due to the extra fields. – gregsdennis Jun 26 '15 at 00:32
  • 1
    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 Sep 04 '15 at 22:51
14

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'}
Joy
  • 8,809
  • 7
  • 38
  • 84
11

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 a YAML solution as suggested by others is good, but it requires a 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 JavaScript 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, the following example will only read the data once and then it will be cached:

data = require(fs.realpathSync(doctree_fp));
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Joshua Richardson
  • 1,410
  • 18
  • 21
  • 11
    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 Dec 08 '13 at 21:58
  • 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 Dec 11 '13 at 23:52
  • +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 Jun 26 '14 at 08:45
  • 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 Jun 27 '14 at 03:13
  • 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 Aug 07 '14 at 19:06
  • 1
    @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 Sep 15 '14 at 07:11
  • @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 `# ...` entries.) That makes it easy enough, I think. – Alexis Wilke Sep 15 '14 at 21:48
  • @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 Sep 16 '14 at 14:39
  • @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 Sep 16 '14 at 21:25
  • 1
    @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 Sep 16 '14 at 23:45
  • 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. – William Entriken Aug 20 '15 at 14:54
  • 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 Jul 03 '16 at 11:13
  • Yeah, no Douglas Crockford does not want people to include comments in JSON, that is why he removed annotations. See my answer. His position is 'do it with some non-interoperable pre-compiler, not in JSON' (eg. Jackson, etc). – Dominic Cerisano Nov 05 '18 at 02:55
  • @KyleSimpson I'm surprised by your statement "JSON is not a regular grammar and thus regular expressions are not enough". Are you sure regular expressions are not enough? The fact that JSON isn't a regular language doesn't necessarily imply that. The subtleties you pointed out (whether /* is escaped or inside a string literal) can certainly be handled by a regular expression. – Don Hatch Apr 23 '19 at 17:14
  • @DonHatch I am sure that regular expressions cannot accurately parse non-regular languages. That's sort of in the definition of the terms: a regular expression parses regular languages. This question is similar to the oft-debated, "can html be parsed with regex?" The emphatic answer is, in a specific case, sure, but in the general case, absolutely not. Regular expressions that have been extended with back-references and recursion can parse more complex languages, but not all non-regular languages. – Kyle Simpson Apr 24 '19 at 18:32
  • @KyleSimpson I understand that a regex can't fully parse the language, but that doesn't necessarily imply your stronger claim that no regex can identify and remove comments, in this language. In lex/yacc terms, I suspect comment identification/removal can be done by lex (the tokenizer, which understands only a regular language) while yacc would be needed to fully parse the language. – Don Hatch Apr 24 '19 at 19:23
11

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

For example, 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

vitaly-t
  • 20,421
  • 5
  • 85
  • 117
  • 13
    It's **not JSON** anymore if you extend the language in custom ways that require a special preprocessor to handle. – meager Sep 05 '18 at 12:41
  • @meagar There was JSON5 spec, which supported comments, among other things. But in the end it never became standard. – vitaly-t Sep 05 '18 at 12:45
8

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

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

{
    // Rainbows
    "unicorn": /* ❤ */ "cake"
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
7

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.

Steve Thomas
  • 298
  • 2
  • 6
  • 10
    `Just make sure your "notex" names don't conflict with any real fields.` is the problem. This is not an arbitrary solution. – William Entriken May 14 '14 at 14:42
  • 4
    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 Sep 15 '14 at 07:07
  • 2
    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 Apr 08 '15 at 03:46
  • 3
    If you're using a schema to validate the JSON, it may fail due to the extra fields. – gregsdennis Jun 26 '15 at 00:30
  • 1
    Some object unmarshallers (e.g. Jackson, under some configurations) throw exceptions on unknown fields. – slim Oct 20 '16 at 09:28
  • How is this different from previous answers? – Peter Mortensen Oct 08 '20 at 16:59
7

There is a good solution (hack), which is valid JSON, but it will not work in all cases (see comments below). 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",
}
anova01
  • 73
  • 1
  • 10
Aurimas
  • 574
  • 4
  • 11
  • 12
    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. –  Feb 12 '14 at 20:24
  • 9
    RFC says: "The names within an object SHOULD be unique". See this error reported at: https://stackoverflow.com/questions/4912386/resolve-jsonexception-duplicate-keys?lq=1 – William Entriken Jun 10 '14 at 15:59
  • 8
    Doing this is an invitation for creating JSON that blows up on you at some random point in the future. – toolbear Aug 07 '14 at 19:00
  • 7
    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 May 26 '15 at 22:26
  • 2
    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 Oct 06 '17 at 18:24
  • 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 Jan 01 '18 at 07:12
  • 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 Jan 16 '18 at 16:44
  • @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 Feb 14 '18 at 02:30
  • json is not ordered, so this will blow up approximately 50% of the time (at least in Go where if the ordering is not defined, it is randomized) – Darshan Chaudhary May 16 '18 at 10:35
7

The practical answer for Visual Studio Code users in 2019 is to use the 'jsonc' extension.

It is practical, because that is the extension recognized by Visual Studio Code to indicate "JSON with comments". Please let me know about other editors/IDEs in the comments below.

It would be nice if Visual Studio Code and other editors would add native support for JSON5 as well, but for now Visual Studio Code only includes support for 'jsonc'.

(I searched through all the answers before posting this and none mention 'jsonc'.)

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Tom
  • 15,404
  • 8
  • 60
  • 70
  • `jsonc` is nice, but unfortunately, you are restricted to // comments. When you need something else , you are kinda broken, too. https://stackoverflow.com/questions/58553633/how-to-convince-vs-code-to-accept-as-comment-in-json-files – GhostCat Oct 25 '19 at 07:52
7

No, JSON cannot have comments directly. However, as suggested by this, you can achieve a similar effect by doing something like

{
    "//name": "Name comment here",
    "name": "Jack",

    "//age": "Age comment here",
    "age": "25"
}

Most JSON parsers will ignore properties that are not mapped.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
datchung
  • 1,586
  • 17
  • 16
7

The JSON specification does not support comments, // or /* */ style.

But some JSON parsing libraries and IDEs support them.

Like:

  1. JSON5
  2. Visual Studio Code
  3. Commentjson
ifelse.codes
  • 1,581
  • 16
  • 14
6

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.

toolbear
  • 6,478
  • 4
  • 31
  • 31
Nick
  • 8,946
  • 6
  • 35
  • 40
  • 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 Jun 01 '17 at 14:04
5

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mark
  • 15,245
  • 6
  • 95
  • 113
5

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

function json_decode_commented ($data, $objectsAsArrays = false, $maxDepth = 512, $opts = 0) {
  $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.

3

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!

Meru-kun
  • 2,402
  • 2
  • 12
  • 21
3

Yes, you can have comments. But I will not recommend whatever reason mentioned above.

I did some investigation, and I found all JSON require methods use the JSON.parse method. So I came to a solution: We can override or do monkey patching around JSON.parse.

Note: tested on Node.js 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 */
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
xdeepakv
  • 6,631
  • 2
  • 16
  • 26
  • 2
    `{ what_if: "I happen to have /* slashes and asterisks */ in my data?" }` – DSimon Dec 22 '16 at 14:24
  • 3
    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 Dec 22 '16 at 15:01
  • 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 Dec 22 '16 at 15:56
  • @DSimon I agree... this seems to work for many cases: `json.replace(/("\/\/.*"|"\/\*(?:.|\n)*?")|(\/\/.*|\/\*(?:.|\n)*?\*\/)/g, "$1")` https://regexr.com/3p39p – Maxim Paperno May 08 '18 at 04:36
3

*.json files are generally used as configuration files or static data, thus the need of comments → some editors like NetBeans accept comments in *.json.

The problem is parsing content to an object. The solution is to always apply a cleaning function (server or client).

###PHP

 $rgx_arr = ["/\/\/[^\n]*/sim", "/\/\*.*?\*\//sim", "/[\n\r\t]/sim"];
 $valid_json_str = \preg_replace($rgx_arr, '', file_get_contents(path . 'a_file.json'));

###JavaScript

valid_json_str = json_str.replace(/\/\/[^\n]*/gim,'').replace(/\/\*.*?\*\//gim,'')
bortunac
  • 3,930
  • 1
  • 26
  • 19
3

Sure you can comment JSON. To read a commented JSON file from JavaScript you can strip comments before parsing it (see the code below). I'm sure this code can be improved, but it is easy to understand for those who use regular expressions.

I use commented JSON files to specify neuron shapes for my synthetic reflex systems. I also use commented JSON to store intermediate states for a running neuron system. It is very convenient to have comments. Don't listen to didacts who tell you they are a bad idea.

fetch(filename).then(function(response) {
    return response.text();
}).then(function(commented) {
    return commented.
        replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '$1').
        replace(/\r/,"\n").
        replace(/\n[\n]+/,"\n");
}).then(function(clean) {
    return JSON.parse(clean);
}).then(function(json) {
    // Do what you want with the JSON object.
});
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jlettvin
  • 1,023
  • 7
  • 12
2

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

{
    "https://schema.org/comment": "this is a comment"
}
MovGP0
  • 5,754
  • 2
  • 40
  • 37
2

This entire thread assumes that adding comments is the only improvement that needs to be made to JSON. If someone doesn't want comments in JSON because it's to be used for serialization, just omit the comments. The same goes for whitespace. But why stop there? Why are quotation marks required in JSON? They add nothing useful.

The only reason I can think of for JSON to be so rigid is if parsing is difficult. But it isn't. Almost any programmer can write a JSON parser, in either direction.

I want JSON to be readable and efficient (brief), and useful for data transmission, configuration files, and lots more. Both of these requirements are satisfied by the following example:

{stringA: stringB, stringC: stringD, [stringE, stringF]}

Shorter than any existing JSON specification, but just as readable and more efficient.

Need to include quotation marks, apostrophes, commas, or brackets in a property or value? Just enclose them in question marks or apostrophes (with backslash escape), just like in JavaScript.

But please make quotation marks optional. Why? Because JSON cannot contain variable or function names (to avoid injection attacks), so quotation marks don't provide any disambiguation. We already know that all the data are strings. So, please, leave out the quotation marks already, unless they are really needed.

David Spector
  • 979
  • 7
  • 17
  • 4
    You might be interested in yaml (https://yaml.org/), a quasi-superset of json which allows for comments and doesn't need quotation marks. – Bill Cheatham Jan 10 '19 at 11:54
  • My fave answer here. Since one can write their own parser, i hopes that someone will (or already has) written a widely-used json parser which eliminates need for quotes, allows comments, and other improvements. How about eliminating brackets and formatting with white space? :) – johny why Apr 13 '20 at 19:13
1

There are other libraries that are JSON compatible, which support comments.

One notable example is the "Hashcorp Language" (HCL)". It is written by the same people who made Vagrant, packer, consul, and vault.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
spuder
  • 14,200
  • 14
  • 77
  • 129
1

I came across this problem in my current project as I have quite a bit of JSON that requires some commenting to keep things easy to remember.

I've used this simple Python function to replace comments & use json.loads to convert it into a dict:

import json, re

def parse_json(data_string):
  result = []
  for line in data_string.split("\n"):
    line = line.strip()
    if len(line) < 1 or line[0:2] == "//":
      continue
    if line[-1] not in "\,\"\'":
      line = re.sub("\/\/.*?$", "", line)
    result.append(line)
  return json.loads("\n".join(result))

print(parse_json("""
{
  // This is a comment
  "name": "value" // so is this
  // "name": "value"
  // the above line gets removed
}
"""))
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
LogicalBranch
  • 3,582
  • 2
  • 16
  • 48
1

Comments are needed in JSON and comments ARE available in at least .NET Core JSON and Newtonsoft Json. Works perfectly.

{
  // this is a comment for those who is ok with being different
  "regular-json": "stuff"...
}
Boppity Bop
  • 7,680
  • 10
  • 58
  • 123
  • I think you should specify the proper syntax to provide a complete answer. – AFract Mar 17 '21 at 14:54
  • If there are JSON parsers out there that parse non-standard JSON, it doesn't mean that adding comments are allowed in JSON. – Evert Mar 21 '21 at 02:56
1

JSON does not support comments, but YAML does support inline comments (no block comments though). Since they are both data files and have similar features, this might be the way to go. In addition, there are resources online like json2yaml.com that can convert JSON to YAML easily

Andrew
  • 380
  • 2
  • 14
0

Yes. You can put comments in a JSON file.

{
    "": "Location to post to",
    "postUrl": "https://example.com/upload/",

    "": "Username for basic auth",
    "username": "joebloggs",

    "": "Password for basic auth (note this is in clear, be sure to use HTTPS!",
    "password": "bloejoggs"
}

A comment is simply a piece of text describing the purpose of a block of code or configuration. And because you can specify keys multiple times in JSON, you can do it like this. It's syntactically correct and the only tradeoff is you'll have an empty key with some garbage value in your dictionary (which you could trim...)

I saw this question years and years ago but I only just saw this done like this in a project I'm working on and I thought this was a really clean way to do it. Enjoy!

nevelis
  • 718
  • 6
  • 17
  • 1
    **N.B.** _"The names within an object SHOULD be unique."_ (Source: [IETF JSON Spec, December 2017](https://tools.ietf.org/html/rfc8259#section-4) – Rounin Jun 15 '20 at 16:54
  • 1
    SHOULD means something different to MUST in a spec. The other answers with comments will break every JSON parser out there. I'd be interested to know if duplicate keys has any bad side effects anywhere. – nevelis Jun 15 '20 at 21:56
  • My point (merely) was not that the names within an object MUST be unique, simply that they SHOULD be unique. After scouring Stack Overflow (and the wider web) for over a day, [I have done my best to come up with my own approach](https://stackoverflow.com/questions/62387123/whats-the-established-approach-for-adding-comments-as-data-to-json-that-can-sur/62397897#62397897). – Rounin Jun 15 '20 at 22:21
  • 1
    Ahh, that's an interesting approach... It requires custom logic to parse, and it moves the comments away from the thing it's describing... ? – nevelis Jun 15 '20 at 22:57
  • 1
    It requires a custom-written reader if you want to see the comments in the right place. Otherwise (ie. normally) there is simply a block of comments at the bottom of the JSON, at root level, with a reserved name, which can be safely ignored and left alone. – Rounin Jun 15 '20 at 23:00
  • When would you *not* want to see the comments in the right place?! – nevelis Jun 18 '20 at 16:35
  • Hey - I think we have a misunderstanding. I don't care about reading the comments in a parsed JSON object in Javascript. I want to 1) be able to read meaningful comments when I'm *editing the source* (ie NOT at runtime), and 2) I don't comments in my JSON to break standards compliant parsers. – nevelis Jun 18 '20 at 16:36
  • I've explained it badly. In the approach I've envisaged, comments are completely absent in any object parsed from the JSON. The comments are, nevertheless visible, in the right place, in a custom-reader (reader / writer / editor) in which you can read, write and edit the JSON file. (And in a non-custom reader, they sit in a block at the bottom of the JSON, out of the way of all of the data). – Rounin Jun 18 '20 at 18:12
0

I really like @eli 's approach, there are over 30 answers but no one has mentioned lists (array). So using @eli 's approach we could do something like:

"part_of_speech": {
  "__comment": [
    "@param {String} type - the following types can be used: ",
      "NOUN, VERB, ADVERB, ADJECTIVE, PRONOUN, PREPOSITION",
      "CONJUNCTION, INTERJECTION, NUMERAL, PARTICLE, PHRASE",
    "@param {String} type_free_form - is optional, can be empty string",
    "@param {String} description - is optional, can be empty string",
    "@param {String} source - is optional, can be empty string"
  ],
  "type": "NOUN",
  "type_free_form": "noun",
  "description": "",
  "source": "https://google.com",
  "noun_class": {
    "__comment": [
      "@param {String} noun_class - the following types can be used: ",
        "1_class, 2_class, 3_class, 4_class, 5_class, 6_class"
    ],
    "noun_class": "4_class"
  }
}
khashashin
  • 859
  • 10
  • 30
-1

Not technically. But you can workaround as follows.

{
  "json": "actual data goes here, comments below",
  "comment1": "Lorem ipsum dolor sit amet",
  "comment2": "consectetur adipiscing elit"
}

Just put the comments in the data. If you number them to make each key path unique, you should have no problems.

Let Me Tink About It
  • 11,866
  • 13
  • 72
  • 169
-4

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);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Maurício Giordano
  • 2,597
  • 3
  • 26
  • 54
  • 7
    Your regexp would remove things like `/*hey*/` even from inside strings. – 6502 Aug 03 '14 at 06:09
  • Good catch! So just change some stuff on regex. – Maurício Giordano Aug 05 '14 at 18:10
  • 1
    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 Aug 07 '14 at 18:57
  • 3
    Regarding *"(there is no standard)"*, there most certainly *is* a standard that defines exactly what JSON is, and there has been since well before this answer was written. – meager Sep 05 '18 at 13:07
  • @meagar I never replied to your comment. I meant standard referring to comments, please let me know if you can find anything related to that here https://www.json.org/json-en.html – Maurício Giordano Jun 01 '20 at 20:36
  • @MaurícioGiordano No, there is nothing there, because JSON doesn't support comments. Of course the standard doesn't have to explicitly state this, any more than it has to explicitly state that it does not have classes. – meager Jun 02 '20 at 00:36
  • This regex still fails for valid inputs. `"\"/*foo*/\"` for instance. Using a regular expression is a really bad idea, as has previously been pointed out. – meager Jun 02 '20 at 00:38