Can comments be used in JSON?

Created 28.10.2008 20:39
Viewed 2.68M times
8255 votes

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

25
Comments
@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. by Michael Burr, 28.10.2008 20:51
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. by driftcatcher, 01.02.2013 15:12
and perhaps this is one reason why TOML was created.. by Alex Nolasco, 01.05.2013 05:22
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!. by Sid, 25.09.2013 11:29
Check out highcharts.com/samples/data/…? and you will see comments. This is JSONP, though, not pure JSON. See my response below. by Sergey Orshanskiy, 07.10.2013 20:39
JSON5 supports comments: stackoverflow.com/a/7901053/108238 by schoetbi, 02.02.2015 11:13
Ruby's json parser is another example of a parser that supports comments. by Ben Crowell, 20.06.2016 17:21
If you want a language for configuration with comments see TOML by schoetbi, 12.09.2016 13:20
Comments are not permitted because it's too late to support comments. Major oversight. Ironically, YAML supports comments. by bvj, 02.08.2017 07:08
oreilly.com/learning/adding-comments-in-json has 2 ways to do add a comment functionality to your JSON file by Flotolk, 08.01.2018 19:32
here is a nice trick gist.github.com/MoOx/5271067 by osama yaccoub, 04.04.2018 15:48
This is why YAML is superior. by Chloe, 17.07.2018 17:07
Look up RFC 4627 and related. by MikeW, 29.10.2018 10:29
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. by hktegner, 31.03.2019 11:08
jsonc files should work, hence the definition: JSON with Comments. by mekb, 21.07.2019 03:19
"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 by Dominic Cerisano, 20.11.2019 15:45
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. by RufusVS, 12.02.2020 17:28
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). by Mike Rosoft, 03.03.2020 11:08
@schoetbi, JSON5 is unofficial. It is not "the 5th version of JSON", despite what its creators would have you believe. See github.com/json5/json5-spec/issues/15 by HullCityFan852, 20.04.2020 00:51
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. by ToolmakerSteve, 30.04.2020 23:40
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? by nabster, 19.05.2020 16:16
manifest.json supports // comments. Just in case someone comes here for this special case, like I did it before. by stackprotector, 17.09.2020 06:48
YAML might be more appropriate if the data need to be human readable. by Mudream, 23.09.2020 10:41
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. by SMBiggs, 20.11.2020 20:44
Android's JSONObject support C-style comments in its parser. by Pointer Null, 08.01.2021 10:38
Show remaining 20 comments
Answers 50
23
6118

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"
            }
         }
      }
   }
}
28.10.2008 21:01
Comments
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...", by Rob Fonseca-Ensor, 03.02.2010 11:41
BTW, the json library for Java google-gson has support for comments. by centic, 01.10.2012 12:21
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 by Juan Mendes, 11.08.2014 12:58
@JuanMendes: you are allowed to have the same key multiple times. by mike3996, 17.12.2014 07:03
We can to select more unique comment keys format for this. Something like {"<!-- glossary -->": "Comment text"} looks ok. "/* glossary */" too. by vp_arth, 19.12.2014 04:21
Why is GlossList not an array (GlossList: [ { .. }, { .. } ])? by Luca Steeb, 12.05.2015 12:58
If you're using a schema to validate the JSON, it may fail due to the extra fields. by gregsdennis, 26.06.2015 00:31
you could also use "//": this looks more native and is still repeatable in the same parent by smnbbrv, 28.08.2015 09:59
@JuanMendes Probably far too late to be of help, but for multi-line comments, make the value of the comment element an array of strings: [ "line 1", <CRLF> "line 2", <CRLF> "line 3" ]. by TripeHound, 09.10.2015 14:11
The thing is it changes the semantic of the JSON, e.g. changing the length of an array. by Qian Chen, 21.12.2015 12:21
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. by Петър Петров, 27.02.2016 13:59
There is JSON5 (5 referring to ECMAScript 5 (and later)). by Peter Mortensen, 19.01.2017 18:42
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. by Ken Mason, 14.08.2017 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 by MIKE, 07.09.2017 17:41
Yea you can try to use {"//": "Your comment"} by danger89, 20.03.2018 19:12
But be careful! Some fully parsing engines need something as @JsonIgnoreProperties annotation, or else they will see unknown field as an error. by Gangnus, 15.05.2018 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 by chb, 17.09.2018 00:45
One of the links in my June 2012 comment no longer works. Another reader (@douglasgross) has provided this current link: groups.yahoo.com/neo/groups/json/conversations/topics/156 by Michael Burr, 27.09.2018 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 by Pranav A., 24.11.2018 22:44
_comment is also the official workaround within composer.json as committed by composer author Seldaek in 98b0af1 by noobish, 02.02.2019 00:12
@RobFonseca-Ensor but what if we will have a field called __comment? We would need to have a new field ___comment. by null, 08.03.2019 17:27
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. by andrew pate, 25.09.2019 13:35
Unfortunately my babel is bitching Error: Unknown option: _comment. by Thielicious, 24.06.2020 22:31
Show remaining 18 comments
11
1952

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)
15.11.2010 09:32
Comments
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. by toolbear, 07.08.2014 19:26
@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. by stakx - no longer contributing, 28.09.2015 07:01
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. by Triynko, 31.10.2017 17:36
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. by cmroanirgo, 21.01.2018 00:29
@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. by stakx - no longer contributing, 21.01.2018 07:48
@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. by d512, 18.06.2019 20:29
@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 changed. by stakx - no longer contributing, 02.07.2019 16:00
@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. by PixelMaster, 10.07.2019 14:38
@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. by d512, 10.07.2019 18:33
@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. by PixelMaster, 10.07.2019 19:51
@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. by d512, 24.07.2019 18:58
Show remaining 6 comments
21
884

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.

23.06.2010 18:20
Comments
The only problem I have with JSON.minify() is that it is really really slow. So I made my own implementation that does the same thing: gist.github.com/1170297 . On some large test files your implementation takes 74 seconds and mine 0.06 seconds. by WizKid, 25.08.2011 09:16
it'd be great if you could submit the suggested alternative algorithm to the github repo for JSON.minify(), so that it can be ported to all the supported langs: github.com/getify/json.minify by Kyle Simpson, 30.08.2011 17:20
Perl's JSON supports # comments. by Johannes Ernst, 14.11.2011 17:36
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. by Marnen Laibow-Koser, 15.12.2011 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. by Marnen Laibow-Koser, 07.03.2012 00:07
You might find it interesting to hear, from the author of JSON, why comments were left out of the spec: youtu.be/-C-JoyNuQJs?t=48m53s by MiniGod, 31.01.2013 03:29
@MiniGod I have already heard Doug's thoughts on this topic many times. I addressed them long ago in my blog post: blog.getify.com/json-comments by Kyle Simpson, 26.02.2013 23:21
@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) by StaxMan, 28.03.2014 22:09
@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. by Marnen Laibow-Koser, 01.04.2014 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? by Marnen Laibow-Koser, 09.04.2014 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. :) by Marnen Laibow-Koser, 09.04.2014 03:16
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. by StaxMan, 09.04.2014 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. :) by Marnen Laibow-Koser, 15.05.2014 05:50
JSON has too much punctuation compared to XML? Can you clarify what you mean there? Here is an example JSON for loading fixtures in Django: [{ "model": "foo.bar", "pk": 1, "fields": { "name": "foo", "customer_number": 12345 }}] The same in XML comes to something like this: <?xml version="1.0" encoding="utf-8"?><django-objects version="1.0"><object pk="1" model="foo.bar"><field type="TextField" name="name">foo</field><field type="IntegerField" name="customer_number">12345</field></object></django-object‌​s> by ManicDee, 16.06.2014 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.) by Marnen Laibow-Koser, 09.07.2014 15:38
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? by Blake, 10.09.2014 16:45
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. by eggmatters, 27.01.2016 19:31
@KyleSimpson 404 on your blog link, update the link if you a new copy by Srinath Ganesh, 24.05.2016 11:42
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. by Remember Monica, 01.05.2017 16:22
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. by JayJay123, 30.05.2017 17:56
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. by Abion47, 12.11.2018 20:20
Show remaining 16 comments
34
222

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!

02.08.2013 13:46
Comments
From the specification: The names within an object SHOULD be unique. by Quentin, 02.08.2013 13:50
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. by p3drosola, 02.08.2013 13:57
"all the implementations handle it the same" — That's a difficult thing to prove. by Quentin, 02.08.2013 14:20
The order of elements in JSON is not guaranteed. That means the "last" item could change! by sep332, 02.08.2013 14:33
@sep332 they are in the case of a hand edited json/config file. by Tracker1, 02.08.2013 14:36
@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." by erdeszt, 02.08.2013 14:37
@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. by Quentin, 02.08.2013 14:39
This clearly violates the spec (see above comments), don't do this. ietf.org/rfc/rfc4627.txt?number=4627 by voidlogic, 02.08.2013 14:39
@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 …). by Quentin, 02.08.2013 14:39
It would be totally reasonable for a parser to discard values of existing keys instead of overwriting them. by Gipsy King, 02.08.2013 14:44
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. by nemetroid, 02.08.2013 14:44
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. by opyh, 02.08.2013 14:47
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. by pdw, 02.08.2013 14:53
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. by deanWombourne, 02.08.2013 14:55
@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. by erdeszt, 02.08.2013 14:58
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. by Brad Choate, 02.08.2013 16:04
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. by nmaier, 02.08.2013 16:19
That is wrong on so many levels I don't even know where to begin. I'll just put that here - pragprog.com/the-pragmatic-programmer/extracts/coincidence - and try to forget what I just saw. by Geoffrey Bachelet, 02.08.2013 18:13
See this question for error case: stackoverflow.com/questions/4912386/… by Paul Tyng, 02.08.2013 18:33
Bad idea - leads to confusion, against spec, not future proof and JSLint disqualifies the JSON. by Praveen Vijayan, 03.08.2013 05:37
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. by Santosh, 03.08.2013 06:13
... 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 **" by Santosh, 03.08.2013 06:21
As we've been working on RFC 4627bis at the IETF in the JSON working group (join us and help! datatracker.ietf.org/wg/json), we have found four different approaches that implementors have used for duplicate names in an object: use the first; use the last; report all of them and let the caller pick one; return an error and stop parsing. If your data can't survive all of those approaches, it won't interoperate in practice. by Joe Hildebrand, 03.08.2013 22:03
Bad hack. It's JSON parser matter. At least IAM policy file (AWS) doesn't accept duplicate JSON key. microsofttranslator.com/bv.aspx?from=&to=en&a=http://… by kyanny, 04.08.2013 03:06
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. by Jeremyfa, 04.08.2013 17:28
Solr uses multiple Keys. This is incompatible with the major opensource search server!!! by fulmicoton, 04.08.2013 22:57
combine that with Eli's answer, and insert duplicate "_comment" keys all around, then you get the best of both worlds. by depoulo, 05.08.2013 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. by Jose Sutilo, 05.08.2013 11:43
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. by asyncwait, 01.11.2013 10:13
"all the implementations handle it the same" - jju has an option to throw on these jsons by alex, 04.01.2014 00:26
This is the most controversial post on SO. by bjb568, 11.04.2014 18:45
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. by gnasher729, 16.10.2014 11:48
You are stepping into the region of implementation dependency. by Derek 朕會功夫, 17.08.2017 20:47
The jsondecode parser of matlab will create api_host and api_host_1 fields, etc .. by user3240484, 29.10.2018 11:57
Show remaining 29 comments
23
483

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+

11.06.2012 08:52
Comments
I thought JSON was to supposed to be more human readable than, say, XML? Comments are for readability. by intrepidis, 14.10.2012 13:00
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... by intrepidis, 14.10.2012 13:04
Removing /* */ comments also made JSON a better subset of YAML. by Schwern, 29.11.2012 07:47
@Schwern But YAML does allow # comments, so your point is kind of muoot by Juan Mendes, 04.04.2013 17:50
@JuanMendes I don't understand why that makes my point about JSON/YAML compatibility moot. What do you think my point was? by Schwern, 04.04.2013 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. by Juan Mendes, 04.04.2013 23:22
@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. by Schwern, 05.04.2013 02:26
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! by Alex Gray, 16.05.2013 22:16
@ChrisNash It was not meant to be more readable than XML, just easily readable by humans. json.org And, JSON is easily readable by humans. Comments add additional information, but don't make it any more or less easy to read for humans. by Oscar Godson, 02.08.2013 18:18
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. by caiosm1005, 23.09.2013 02:28
@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. by Artur Czajka, 24.09.2013 12:22
@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 :) by caiosm1005, 04.10.2013 02:42
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. by rakehell, 29.05.2014 17:52
"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. by adelphus, 12.06.2014 14:22
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. by toolbear, 07.08.2014 19:24
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. by Craig, 15.09.2014 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? by Craig, 15.09.2014 06:54
Not having comments in JSON feels wrong. Formatting (spaces, linefeeds) are allowed in JSON and there is no fundamental difference between formatting and comments. by Johannes Overmann, 29.01.2015 09:55
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. by Phil Goetz, 14.05.2015 17:24
@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. by Winter, 11.08.2017 12:37
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. by Peter Flynn, 31.08.2017 13:27
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. by Mac, 24.08.2018 15:41
I'm assuming that JSMin refers to the JavaScript minifier on Crockford's site at crockford.com/jsmin.html , is that correct? by cowlinator, 19.11.2019 21:02
Show remaining 18 comments
8
279

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.

20.03.2014 15:26
Comments
if you look at the spec you'd see that it's a superset of json. you can convert from/to json. by laktak, 12.06.2014 14:53
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. by konsolebox, 30.06.2014 19:20
Sorry about that, @konsolebox. Perhaps you might reconsider your "well-defined JSON is your opinion" view after reading ecma-international.org/publications/files/ECMA-ST/ECMA-404.p‌​df It is a real standard and devs implementing their own "special" versions leads to fragmentation, confusion and a lot of wasted time. Look at the mess web developers are left with when writing code just because each browser implements slightly different versions of standards. The JSON language may not be perfect, but fragmentation is worse. And yes, that's just a opinion and you're free to disagree. by adelphus, 09.07.2014 16:02
I admire your gumption, but you're kinda re-inventing YAML. If you want lot's of flexibility and human readability, use YAML (don't actually: stackoverflow.com/questions/450399/…) or stick with curmudgeony, yet unambiguous JSON. by toolbear, 07.08.2014 18:25
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. by Matt, 10.02.2015 15:15
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) by jebbie, 06.04.2016 14:20
"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. by RobG, 03.01.2019 00:32
Tell that to the Jest developers (e.g., configuration file package.json). by Peter Mortensen, 08.10.2020 17:17
Show remaining 3 comments
16
150

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

31.08.2011 02:24
Comments
Note that the converse is not true (valid YAML !=> valid JSON) by g33kz0r, 11.09.2012 04:01
@g33kz0r Correct, hence my description of YAML as a near-superset of JSON. by Marnen Laibow-Koser, 12.09.2012 14:58
@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. by Marnen Laibow-Koser, 28.03.2014 12:57
Downside: yaml library isn't shipped with Python. by Bleeding Fingers, 15.04.2014 10:06
@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. by Marnen Laibow-Koser, 13.08.2014 19:25
@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. by toolbear, 17.08.2014 23:32
@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. by Marnen Laibow-Koser, 18.08.2014 20:38
@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. by toolbear, 25.08.2014 11:45
@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. by toolbear, 25.08.2014 11:56
@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. by Marnen Laibow-Koser, 13.09.2014 00:58
yaml >> json . And python has a good yaml library. I have to roll my own in Scala - but still worth it. by StephenBoesch, 02.10.2016 05:35
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. by TamusJRoyce, 26.12.2018 17:22
@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. by Marnen Laibow-Koser, 27.12.2018 21:58
something that works is a valid solution. Even if not optimal. Maybe you are developing and temporarily need comments. Then refactor it out. by TamusJRoyce, 27.12.2018 22:44
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. by TamusJRoyce, 14.02.2019 00:58
@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. by Marnen Laibow-Koser, 14.02.2019 01:00
Show remaining 11 comments
0
121

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.

28.10.2008 20:42
2
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.

26.10.2011 09:46
Comments
Groovy has some built-in classes for handling JSON. JsonSlurper can handle comments. Of course, comments are not allowed in the official spec, so this behavior in any parser is non-standard and non-portable. by izrik, 06.11.2015 21:47
Newtonsoft Json.NET also support C-style comments with no problems by Max, 17.04.2020 01:19
7
76

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.

28.07.2010 18:38
Comments
Is JSON schema alive? It exists but is it supported by any known library? by Munhitsu, 29.10.2012 14:31
yes, the json-schema google group is fairly active and I would recommend JSV for a good JavaScript implementation of a JSON Schema validator. by raffel, 27.11.2012 11:34
This only helps with structured documentation, not ad-hoc documentation by Juan Mendes, 04.04.2013 17:47
If you use clojure (and I'm sure you don't) there's a reasonably featured open-source JSON schema parser here: github.com/bigmlcom/closchema by charleslparker, 15.04.2013 13:50
@Munhitsu Manatee.Json (.Net) extensively supports JSON schema. by gregsdennis, 26.06.2015 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. */. by jgmjgm, 08.12.2017 11:22
Perhaps time for an update? E.g. how widely it is adopted, etc. by Peter Mortensen, 08.10.2020 16:34
Show remaining 2 comments
1
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.

06.02.2014 20:44
Comments
is this reversible ? what if you load the file and write it back ? by R. Du, 19.11.2020 18:11
0
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

27.11.2015 19:35
4
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"
}
22.06.2017 12:58
Comments
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 by gutte, 01.11.2017 20:44
This method breaks some libraries, which require that the key must be unique. I'm working around that issue by numbering the comments. by MovGP0, 19.01.2018 11:45
good comment, I found this question on SO ... this part seems not to be covered by the spec stackoverflow.com/questions/21832701/… by mana, 20.01.2018 19:36
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" } by MovGP0, 09.03.2018 16:29
7
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.

09.04.2010 22:30
Comments
Probably the best suggestion so far, though still an issue for keeping files as an interchange format, as they need pre-processing before use. by Orbling, 25.02.2011 11:04
I agree and have written a JSON parser in Java, available at www.SoftwareMonkey.org, that does exactly that. by Lawrence Dol, 28.07.2012 01:51
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.*/" } by stofl, 27.07.2013 12:09
"...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. by Kyle Simpson, 08.12.2013 21:55
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. by toolbear, 07.08.2014 19:32
One liner JS-compatible regex: myJson.replace(/("\/\/.*"|"\/\*(?:.|\n)*?")|(\/\/.*|\/\*(?:.‌​|\n)*?\*\/)/g, "$1") regexr.com/3p39p by Maxim Paperno, 08.05.2018 04:34
@MaximPaperno Nope, no good: regexr.com/5fvda by JLRishe, 10.11.2020 17:48
Show remaining 2 comments
4
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.

25.07.2014 13:43
Comments
It is hard to understand why someone would have problem with stating a fact. by dvdmn, 29.07.2014 14:17
I would assume someone took exception because the above is no longer JSON, or is invalid JSON. Perhaps adding a short disclaimer would appease. by toolbear, 07.08.2014 18:12
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. by John, 20.08.2014 16:48
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. by gman, 06.06.2019 03:35
3
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.

24.11.2015 04:34
Comments
Could you please add an example? Then you may actually need those extra characters. by dgilperez, 17.12.2015 00:15
It's required by the SO guidelines to provide an actual answer. Link-only answers are not desired. You can check the guidelines stackoverflow.com/help/how-to-answer by dgilperez, 29.12.2015 20:06
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. by dgilperez, 30.12.2015 11:21
5
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.

28.10.2008 23:05
Comments
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. :-/ by StaxMan, 01.09.2009 18:20
@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. by Camilo Martin, 11.12.2010 09:03
Metadata belongs in metadata constructs (e.g. HTML <meta> tags), not comments. Abusing comments for metadata is just a hack used where no true metadata construct exists. by Marnen Laibow-Koser, 06.09.2011 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. by gaborous, 25.06.2013 14:50
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. by toolbear, 07.08.2014 19:35
1
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.

25.06.2013 14:48
Comments
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. by toolbear, 07.08.2014 19:14
5
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.

22.06.2011 13:09
Comments
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. by Marnen Laibow-Koser, 19.10.2011 21:35
how many languages do you think supports YAML out of the box compared to json ? by mmm, 13.01.2012 13:26
@Hamidam Over a dozen languages support yaml: yaml.org - but you're right to ask how many have support built-in, without the need for a third-party library dependency. Looks like Ruby 1.9.2 does. Anyone know of others? And which languages ship support for json by default? by nealmcb, 21.03.2012 15:53
YAML interop is a lie: stackoverflow.com/questions/450399/… . If your instinct is to use JSON for configuration files, follow it. by toolbear, 07.08.2014 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. by Pascal Ganaye, 02.12.2015 18:24
9
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",
}
28.01.2014 15:04
Comments
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. by User, 12.02.2014 20:24
RFC says: "The names within an object SHOULD be unique". See this error reported at: stackoverflow.com/questions/4912386/… by William Entriken, 10.06.2014 15:59
Doing this is an invitation for creating JSON that blows up on you at some random point in the future. by toolbear, 07.08.2014 19:00
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. by Mark Lakata, 26.05.2015 22:26
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. by gnasher729, 06.10.2017 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. by Christian Hujer, 01.01.2018 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. by ggb667, 16.01.2018 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. by Rolf, 14.02.2018 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) by Darshan Chaudhary, 16.05.2018 10:35
Show remaining 4 comments
1
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!

11.12.2012 01:37
Comments
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. by toolbear, 07.08.2014 19:19
1
32

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

See another Stack Overflow question.

04.08.2012 00:56
Comments
And I believe that is why I see a comment in a screenshot on this ASP.NET vNext preview page (under package.json): blogs.msdn.com/b/webdev/archive/2014/06/03/… although I haven't found anything in the spec yet. by webXL, 17.09.2014 21:54
4
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.

18.01.2011 21:57
Comments
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. by toolbear, 07.08.2014 19:31
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. by David, 07.08.2014 23:37
It's bad voodoo to serve up commented, and thus invalid JSON, which dojo.xhrGet() implicitly encourages by accepting. by toolbear, 08.08.2014 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. by Craig, 15.09.2014 07:03
0
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.

20.07.2015 09:26
4
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;
24.04.2014 17:23
Comments
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. by William Entriken, 24.09.2014 18:15
For greater comment density, couldn't you encode your comment in ternary and use space, tab, and newline to steg it? by Claire Nielsen, 26.09.2018 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. by Jeff K, 23.09.2019 18:04
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. by William Entriken, 26.09.2019 20:22
0
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.

07.10.2013 20:37
1
20

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.

17.06.2019 07:18
Comments
This is pretty funny. by Evert, 21.03.2021 02:57
4
14

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

{

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

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

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

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

}
29.10.2013 10:30
Comments
You've emulated an INI file structure in JSON. Please, put down your Golden Hammer. by Artur Czajka, 18.11.2013 16:53
RFC says "The names within an object SHOULD be unique". Also see this person that is having an error parsing JSON like the above: stackoverflow.com/questions/4912386/… by William Entriken, 10.06.2014 15:58
If you're using a schema to validate the JSON, it may fail due to the extra fields. by gregsdennis, 26.06.2015 00:32
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? by Jazimov, 04.09.2015 22:51
4
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."
    }
}
19.06.2018 14:04
Comments
The "reasoning" link is broken. Any chance of finding a current link to it? by Don Hatch, 23.04.2019 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. by fyngyrz, 24.04.2019 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. by Dominic Cerisano, 14.07.2019 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. by fyngyrz, 28.01.2020 14:41
0
18

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

26.08.2016 17:31
16
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));
06.12.2013 21:46
Comments
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. by Kyle Simpson, 08.12.2013 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. by Joshua Richardson, 11.12.2013 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... by Alexis Wilke, 26.06.2014 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. by Joshua Richardson, 27.06.2014 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. by toolbear, 07.08.2014 19:06
@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... by Craig, 15.09.2014 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 # <line#> ... entries.) That makes it easy enough, I think. by Alexis Wilke, 15.09.2014 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. by Craig, 16.09.2014 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.) by Alexis Wilke, 16.09.2014 21:25
@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. ;-) by Craig, 16.09.2014 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. by William Entriken, 20.08.2015 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. by Florian F, 03.07.2016 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). by Dominic Cerisano, 05.11.2018 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. by Don Hatch, 23.04.2019 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. by Kyle Simpson, 24.04.2019 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. by Don Hatch, 24.04.2019 19:23
Show remaining 11 comments
3
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.

19.11.2020 07:35
Comments
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? by Xavi Montero, 28.03.2021 13:53
If you create your own standard, you are the only in the world using it. Something like JSON5 is probably better. by Audrius Meskauskas, 28.03.2021 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. by Xavi Montero, 29.03.2021 19:00
6
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.

28.11.2013 13:48
Comments
Just make sure your "notex" names don't conflict with any real fields. is the problem. This is not an arbitrary solution. by William Entriken, 14.05.2014 14:42
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. by Craig, 15.09.2014 07:07
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. by olivr, 08.04.2015 03:46
If you're using a schema to validate the JSON, it may fail due to the extra fields. by gregsdennis, 26.06.2015 00:30
Some object unmarshallers (e.g. Jackson, under some configurations) throw exceptions on unknown fields. by slim, 20.10.2016 09:28
How is this different from previous answers? by Peter Mortensen, 08.10.2020 16:59
Show remaining 1 comments
3
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'}
27.11.2014 11:39
Comments
Note that the json is not a valid JSON anymore when it includes these propriety comments. by Roy Prins, 31.07.2019 12:12
In which context does strip-json-comments run? Node.js? by Peter Mortensen, 08.10.2020 17:06
@PeterMortensen i tried for node.js. you can try whether works on client-side js. by Joy, 08.10.2020 23:44
2
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

29.12.2015 05:12
Comments
It's not JSON anymore if you extend the language in custom ways that require a special preprocessor to handle. by meagar, 05.09.2018 12:41
@meagar There was JSON5 spec, which supported comments, among other things. But in the end it never became standard. by vitaly-t, 05.09.2018 12:45
0
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.

16.04.2017 17:32
1
8

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

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

{
    // Rainbows
    "unicorn": /* ❤ */ "cake"
}
03.07.2014 05:06
Comments
Might as well minify that JSON while you're at it. See @kyle-simpson's answer about JSON.minify. by toolbear, 07.08.2014 18:54
1
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.

19.07.2014 10:29
Comments
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. by rob, 01.06.2017 14:04
2
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
06.11.2019 13:43
Comments
VS Code .jsonc FTW 🙌 by Quang Van, 13.01.2020 15:28
JSON5 isn't the fifth version of JSON. by Peter Mortensen, 08.10.2020 16:51
1
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'.)

23.01.2019 14:15
Comments
jsonc is nice, but unfortunately, you are restricted to // comments. When you need something else , you are kinda broken, too. stackoverflow.com/questions/58553633/… by GhostCat, 25.10.2019 07:52
1
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.

09.07.2019 13:38
Comments
How is this different from previous answers? by Peter Mortensen, 08.10.2020 16:48
0
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.

07.11.2015 13:59
4
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 */
}
08.12.2016 11:21
Comments
{ what_if: "I happen to have /* slashes and asterisks */ in my data?" } by DSimon, 22.12.2016 14:24
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". by DSimon, 22.12.2016 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. by xdeepakv, 22.12.2016 15:56
@DSimon I agree... this seems to work for many cases: json.replace(/("\/\/.*"|"\/\*(?:.|\n)*?")|(\/\/.*|\/\*(?:.|\‌​n)*?\*\/)/g, "$1") regexr.com/3p39p by Maxim Paperno, 08.05.2018 04:36
1
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,'')
08.07.2018 13:11
Comments
What is a "jcomment"? by Peter Mortensen, 08.10.2020 16:57
1
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!

25.03.2016 02:46
Comments
solution category == 'transform through preproc' by dreftymac, 04.12.2016 12:59
0
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.
});
19.03.2019 09:52
0
2

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

{
    "https://schema.org/comment": "this is a comment"
}
11.02.2016 18:41
7
-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);
07.07.2014 20:08
Comments
Your regexp would remove things like /*hey*/ even from inside strings. by 6502, 03.08.2014 06:09
Good catch! So just change some stuff on regex. by Maurício Giordano, 05.08.2014 18:10
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. by toolbear, 07.08.2014 18:57
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. by meagar, 05.09.2018 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 json.org/json-en.html by Maurício Giordano, 01.06.2020 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. by meagar, 02.06.2020 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. by meagar, 02.06.2020 00:38
Show remaining 2 comments
2
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.

16.12.2018 00:39
Comments
You might be interested in yaml (yaml.org), a quasi-superset of json which allows for comments and doesn't need quotation marks. by Bill Cheatham, 10.01.2019 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? :) by johny why, 13.04.2020 19:13
0
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.

02.07.2015 19:48