Can comments be used in JSON?
Asked Answered
I

62

9532

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

Illicit answered 28/10, 2008 at 20:39 Comment(22)
@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.Adi
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.Park
Check out highcharts.com/samples/data/…? and you will see comments. This is JSONP, though, not pure JSON. See my response below.Kessel
JSON5 supports comments: https://mcmap.net/q/32993/-can-comments-be-used-in-jsonRockie
If you want a language for configuration with comments see TOMLRockie
Comments are not permitted because it's too late to support comments. Major oversight. Ironically, YAML supports comments.Tree
oreilly.com/learning/adding-comments-in-json has 2 ways to do add a comment functionality to your JSON fileRundle
here is a nice trick gist.github.com/MoOx/5271067Neille
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.Clintclintock
"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), 2012Bilander
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).Scleroprotein
@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/15Capablanca
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.Pohl
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?Smollett
manifest.json supports // comments. Just in case someone comes here for this special case, like I did it before.Bicarbonate
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.Dannielledannon
If its jsonschema, a variant, use {"$comment" : "My comment"}Yulma
@DominicCerisano I realize you're just quoting the creator, and this has probably already been retread a thousand times, but this problem isn't "fixed" by not having comments, you can still put directives in objects as e.g., string literals, parsed by something a specific way. Trying to prevent this problem is futile, sorry. Looking back through history, and in the recent past (catkin -> CMake -> Makefile), (Helm -> Kubernetes -> Dockerfile), it's inevitable that some frontend will try and inject itself into every format, for better or for worse.Regain
Re: "Data vs Configuration": If I make a program that sends a command to a different program, is the parameters of that command "data" or "configuration"? It's data from the perspective of the program making the command, it's configuration from the perspective of the program using that information. This whole "JSON shouldn't be used for configuration" argument is based on semantics that only take in one side of the story, it just feels very poorly thought out. Theoretically and practically, a mistake, sorry to say.Regain
Comments were removed from JSON by design. According: web.archive.org/web/20120507093915/https://plus.google.com/…Szczecin
Sadly the wayback entry has vanished. Keeping it in here since it at least encodes the date and maybe it will show up again someday. Also certainly removing comments did not prevent all abuses, but one does what one can to send a message to abusers ('quit that, it breaks interoperability')Bilander
If you would need comments, do not use JSON: it is to be read by machines, not humans. Your choice on JSON is the mistake. Yes, I am talking to you, NPM.Nock
P
7069

No.

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

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

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

But if you decided to:

{
   "_comment": "comment text goes here...",
   "glossary": {
      "title": "example glossary",
      "GlossDiv": {
         "title": "S",
         "GlossList": {
            "GlossEntry": {
               "ID": "SGML",
               "SortAs": "SGML",
               "GlossTerm": "Standard Generalized Markup Language",
               "Acronym": "SGML",
               "Abbrev": "ISO 8879:1986",
               "GlossDef": {
                  "para": "A meta-markup language, used to create markup languages such as DocBook.",
                  "GlossSeeAlso": ["GML", "XML"]
               },
               "GlossSee": "markup"
            }
         }
      }
   }
}
Porfirioporgy answered 28/10, 2008 at 21:1 Comment(21)
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...",Goulder
BTW, the json library for Java google-gson has support for comments.Desjardins
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 prpoertiesSeline
We can to select more unique comment keys format for this. Something like {"<!-- glossary -->": "Comment text"} looks ok. "/* glossary */" too.Courtship
Why is GlossList not an array (GlossList: [ { .. }, { .. } ])?Alembic
If you're using a schema to validate the JSON, it may fail due to the extra fields.Allusive
you could also use "//": this looks more native and is still repeatable in the same parentAnalogize
@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" ].Sweat
The thing is it changes the semantic of the JSON, e.g. changing the length of an array.Zak
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.Unreal
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.Eph
If you are returning the json via api then the client should be using the HTTP Options verb to read the json descriptions/commentsCairns
But be careful! Some fully parsing engines need something as @JsonIgnoreProperties annotation, or else they will see unknown field as an error.Chandos
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 CrockfordGalliett
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/156Adi
@RobFonseca-Ensor but what if we will have a field called __comment? We would need to have a new field ___comment.Balinese
A pseudo attribute will add duplicated keys if you add comments to different items on the same level.Monogenetic
XML is data only as well, still, it has possibility to include comments.Hankins
With a full understanding of all these issues, we went ahead and implemented a pre-processor for our JSON files that allows us to add comments. That way we can use comments in our JSON, but the code never sees them.Gesture
Note that JSON got some inspiration from REBOL, which can be used to store only data (or code, depending); but still, its syntax allows comments (prefixed with ;).Overshine
Surprisingly, Microsoft Azure Policy do support _comment in metadata section.Ailbert
O
2161

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)
Oedema answered 15/11, 2010 at 9:32 Comment(11)
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.Gradate
@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.Oedema
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.Idette
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.Karlise
@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.Oedema
@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.Geography
@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.Oedema
@Geography 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.Dibbell
@Dibbell 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.Geography
@Geography 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.Dibbell
@Dibbell 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.Geography
P
1005

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.

Poynter answered 23/6, 2010 at 18:20 Comment(20)
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.Gazehound
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.minifyPoynter
Perl's JSON supports # comments.Toughminded
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.Intercede
@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.Intercede
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=48m53sShouldst
@Shouldst 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-commentsPoynter
@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)Platinous
@Platinous 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.Intercede
@Platinous 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?Intercede
@Platinous "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. :)Intercede
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.Platinous
@Platinous "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. :)Intercede
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-objects>Facetiae
@Facetiae 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.)Intercede
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?Girard
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.Trin
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.Koziol
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.Nonstandard
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.Corenecoreopsis
N
569

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+

Nils answered 11/6, 2012 at 8:52 Comment(26)
I thought JSON was to supposed to be more human readable than, say, XML? Comments are for readability.Cauda
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...Cauda
@Schwern But YAML does allow # comments, so your point is kind of muootSeline
@JuanMendes I don't understand why that makes my point about JSON/YAML compatibility moot. What do you think my point was?Sassafras
@Sassafras 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.Seline
@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.Sassafras
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!Remembrancer
@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.Hoem
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.Mercurialism
@Mercurialism 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.Nils
@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 :)Mercurialism
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.Rolfe
"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.Nourishment
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.Gradate
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.Kenwee
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?Kenwee
Not having comments in JSON feels wrong. Formatting (spaces, linefeeds) are allowed in JSON and there is no fundamental difference between formatting and comments.Roving
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.Hurley
@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.Quiet
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.Chemmy
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.Admass
It's frankly irrelevant what the original JSON author thought at this point. We are where we are in 2022, and it looks nothing like what Doug Crockford envisioned. No disrespect for this man intended.Steroid
@Steroid The first part of your comment is true: does not matter what original author thought. The second part: no disrespect intended is not: it's a non starter design-wise to consider commenting superfluous. Why have documentation - that's not needed either ..?Pillbox
I expected the reason to be bad, but not this ridiculous, TBH. It's killing flies with a cannon and exploding 50 nearby buildings.Shumaker
@Quiet that reasoning is even worse, to the point where I'm wondering if you ever touched code. Otherwise you'd know that certain tools/libraries enforce JSON files on you, even if you prefer YAML, TOML and a bunch of other formats yourself. Why would I abandon using VSCode, which is an amazing tool otherwise, just because some of their config files require JSON format in which I'd like to keep certain lines commented at this time?Shumaker
@Shumaker You could have used the time you spent here complaining to implement comment preprocessing for whatever JSON parser you are using. It's been 6 years since I've written this comment, a lot have changed but I still think comments in JSON is bad practice and I'm glad the standard maintains that.Quiet
A
384

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.

Archiplasm answered 20/3, 2014 at 15:26 Comment(8)
if you look at the spec you'd see that it's a superset of json. you can convert from/to json.Archiplasm
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. @Nourishment 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.Hallam
Sorry about that, @konsolebox. Perhaps you might reconsider your "well-defined JSON is your opinion" view after reading ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf It is a real standard and devs implementing their own "special" versions leads to fragmentation, confusion and a lot of wasted time. Look at the mess web developers are left with when writing code just because each browser implements slightly different versions of standards. The JSON language may not be perfect, but fragmentation is worse. And yes, that's just a opinion and you're free to disagree.Nourishment
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: #450899) or stick with curmudgeony, yet unambiguous JSON.Gradate
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.Refrigerate
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)Lon
"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.Teratogenic
Tell that to the Jest developers (e.g., configuration file package.json).Daukas
S
242

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!

Schlueter answered 2/8, 2013 at 13:46 Comment(25)
From the specification: The names within an object SHOULD be unique.Ablution
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.Schlueter
The order of elements in JSON is not guaranteed. That means the "last" item could change!Chops
@Ablution 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."Deflagrate
@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.Ablution
This clearly violates the spec (see above comments), don't do this. ietf.org/rfc/rfc4627.txt?number=4627Riddell
@Deflagrate — 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 …).Ablution
It would be totally reasonable for a parser to discard values of existing keys instead of overwriting them.Martamartaban
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.Norther
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.Hereby
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.Bobbee
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.Diskin
@Ablution 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.Deflagrate
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.Touraco
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.Courier
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.Sangfroid
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.Electronarcosis
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.Delogu
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://…Toilworn
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.Pedagogics
combine that with Eli's answer, and insert duplicate "_comment" keys all around, then you get the best of both worlds.Kristof
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.Nonfiction
"all the implementations handle it the same" - jju has an option to throw on these jsonsPascoe
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.Hoban
This is a horrible answer, and I'm surprised that so many people assumed JSON was a Javascript-only format. I know it was a 2013 discussion, but it was also wrong in 2013.Scorch
I
201

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

Intercede answered 31/8, 2011 at 2:24 Comment(16)
Note that the converse is not true (valid YAML !=> valid JSON)Pillow
@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.Intercede
@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.Intercede
@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.Gradate
@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.Intercede
@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.Gradate
@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.Gradate
@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.Intercede
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.Bursar
@Bursar 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.Intercede
@toolbear "A pragmatic format with perfect implementations is better than an ideal format with imperfect implementations." This seems short sighted to me. I find myself here because my time is being wasted, yet again, by my inability to document, via comment, a subtlety in a configuration file in json. The amount of such time wasted, if we stick to json, is unbounded into the future, which doesn't sit well with me. The amount of time wasted by e.g. YAML's imperfect implementations is bounded: it lasts only until those bugs are fixed, and then we have a better future, forever, going forward.Tutelary
YAML causes more problems than it solves.Caricature
@Caricature Only if you try to use it as a programming language, which you shouldn't (nor should you use JSON or XML that way—see the horror that is Ant). Most of the corner cases in that document that you linked to seem to come from attempting to do that. That seems to be unfortunately common in some devops tooling (Ansible does a truly ridiculous amount of it, for example). If you stick to using YAML for simple structured data, it's very reliable. It's never caused me any problems at all in well over a decade of using it. I would choose it over JSON in that use case every time.Intercede
@MarnenLaibow-Koser I will admit that I have some severe trauma from Ansible and production Kubernetes abusing YAML. And Ant is disgusting. Still, I don't like that YAML makes so many unnecessary assumptions; what is a boolean, string, or number is completely arbitrary unless you memorise the spec, which is unreasonable because it's longer than JSON and XML spec combined. There's also the issue that it's RCE-capable as a feature by default, which means one missed PR from a junior is now an exploit. It really isn't terrible for basic projects, but it's a big no-no for anything internet-facing.Caricature
@Caricature AFAIK the YAML RCE vulnerabilities were patched long ago, and they’re not an issue anyway unless you accept untrusted YAML from a stranger and use !object syntax. In years of working with YAML, I’ve never had to do either one of those things (YAML works better for local files, but JSON works better for untrusted data coming in over the Internet; VCR’s cassette files use !object syntax but they’re never edited by humans or run untrusted). Ansible’s use of YAML is surely unfortunate, and I’m sorry it’s turned you off to what in its proper application is a very nice language.Intercede
@Caricature I’ll also say that I’ve never had the slightest issue with YAML’s implicit datatyping; it mostly works as one would expect. There’s no need to memorize the spec unless you’re really abusing the language. When in doubt, you can quote explicitly, but it’s very rarely necessary—which is actually one thing I like about it. 99% of the quotation marks in JSON are on things that are already obviously strings, so they’re just noise.Intercede
C
146

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.

Campeche answered 28/10, 2008 at 20:42 Comment(0)
R
127

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.

Rockie answered 26/10, 2011 at 9:46 Comment(3)
Groovy has some built-in classes for handling JSON. JsonSlurper can handle comments. Of course, comments are not allowed in the official spec, so this behavior in any parser is non-standard and non-portable.Back
Newtonsoft Json.NET also support C-style comments with no problemsVindicate
IMHO this is the best answer to the question, because it includes a good list of many alternative parsers that do have support. Hacks using duplicate or extraneous keys should not be encouraged, if you want/need comments you should use an alternative standard.Dished
Q
104

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"
}
Qp answered 22/6, 2017 at 12:58 Comment(4)
FYI, Firebase Realtime Database does not allow the use of '/' in a key. so this can be a nice convention for your own use, but you cannot do it in FirebaseMagnusson
This method breaks some libraries, which require that the key must be unique. I'm working around that issue by numbering the comments.Dipterous
good comment, I found this question on SO ... this part seems not to be covered by the spec #21833201Qp
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" }Dipterous
W
95

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.

Whitish answered 28/7, 2010 at 18:38 Comment(4)
yes, the json-schema google group is fairly active and I would recommend JSV for a good JavaScript implementation of a JSON Schema validator.Whitish
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/closchemaRommel
@Munhitsu Manatee.Json (.Net) extensively supports JSON schema.Allusive
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. */.Punchdrunk
B
89

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

From the creator of JSON:

I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't. - Douglas Crockford, 2012

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

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

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

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

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

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

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

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

Bilander answered 27/11, 2015 at 19:35 Comment(0)
S
86

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.

Syncytium answered 6/2, 2014 at 20:44 Comment(1)
is this reversible ? what if you load the file and write it back ?Campanula
S
58

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.

Scupper answered 25/7, 2014 at 13:43 Comment(2)
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.Hocker
Could become problematic if the parsers implementation changed.Nam
C
51

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.

Challenging answered 9/4, 2010 at 22:30 Comment(7)
Probably the best suggestion so far, though still an issue for keeping files as an interchange format, as they need pre-processing before use.Alodi
I agree and have written a JSON parser in Java, available at www.SoftwareMonkey.org, that does exactly that.Septimal
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.*/" }Logician
"...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.Poynter
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.Gradate
One liner JS-compatible regex: myJson.replace(/("\/\/.*"|"\/\*(?:.|\n)*?")|(\/\/.*|\/\*(?:.|\n)*?\*\/)/g, "$1") regexr.com/3p39pSynod
"If you do that then JSON files could be used as configuration files." If you do that, it won't be a (valid) JSON file anymore.Sheriesherif
H
45

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

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

Source:

JSON does not have comments. A JSON encoder MUST NOT output comments. A JSON decoder MAY accept and ignore comments.

Comments should never be used to transmit anything meaningful. That is what JSON is for.

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

Hellbent answered 25/6, 2013 at 14:48 Comment(1)
Crockford later went on to write: "Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser." See @kyle-simpson's answer about JSON.minify for more info.Gradate
M
44

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.

Monomolecular answered 28/10, 2008 at 23:5 Comment(3)
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. :-/Platinous
@Platinous 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.Ridings
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.Intercede
S
39

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.

Sw answered 19/11, 2020 at 7:35 Comment(4)
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?Krick
If you create your own standard, you are the only in the world using it. Something like JSON5 is probably better.Matrilocal
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.Krick
JSON5 is not "the new standard" - It's a separate standard developed by separate people.Coralloid
S
38

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

See another Stack Overflow question.

Suppletory answered 4/8, 2012 at 0:56 Comment(1)
And I believe that is why I see a comment in a screenshot on this ASP.NET vNext preview page (under package.json): blogs.msdn.com/b/webdev/archive/2014/06/03/… although I haven't found anything in the spec yet.Distaff
B
37

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.

Bookworm answered 22/6, 2011 at 13:9 Comment(4)
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.Intercede
@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?Iceberg
YAML interop is a lie: #450899 . If your instinct is to use JSON for configuration files, follow it.Gradate
Yaml has wide support, but the spec is complex and leads to bugs and arbitrary code execution. YAML: probably not so great after all, noyaml, and The yaml document from hell chronicle the flaws of yaml.Milano
N
37

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!

Narcho answered 11/12, 2012 at 1:37 Comment(1)
No need to fragment JSON. JSON with comments is no longer JSON. But it's perfectly acceptable to annotate your JSON with comments, so long as you make sure to strip them out before parsing or transmitting it. It should never be the receiver's responsibility to do this.Gradate
P
35

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.

Palmapalmaceous answered 24/11, 2015 at 4:34 Comment(0)
S
28

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

Other JavaScript toolkits may work similarly.

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

Skulk answered 18/1, 2011 at 21:57 Comment(4)
No. Not this. JSON doesn't have comments. If you choose to annotate your JSON with comments, minify it before parsing or transmitting. This shouldn't be the receiver's responsibility.Gradate
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.Skulk
It's bad voodoo to serve up commented, and thus invalid JSON, which dojo.xhrGet() implicitly encourages by accepting.Gradate
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.Kenwee
K
27

You can have comments in JSONP, but not in pure JSON. I've just spent an hour trying to make my program work with this example from Highcharts.

If you follow the link, you will see

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

Since I had a similar file in my local folder, there were no issues with the Same-origin policy, so I decided to use pure JSON… and, of course, $.getJSON was failing silently because of the comments.

Eventually I just sent a manual HTTP request to the address above and realized that the content-type was text/javascript since, well, JSONP returns pure JavaScript. In this case comments are allowed. But my application returned content-type application/json, so I had to remove the comments.

Kessel answered 7/10, 2013 at 20:37 Comment(0)
H
27

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."
    }
}
Herv answered 19/6, 2018 at 14:4 Comment(2)
The reasoning is not foolish, and you just proved it. Implementing comments as tags preserves interoperability. This is exactly why Crockford wanted comments to be parsed as tags. Now everything is just a tag and parsed the same way.Bilander
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.Herv
M
27

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.

Morris answered 17/6, 2019 at 7:18 Comment(0)
I
26

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

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

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

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

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


First, canonicalize your JSON by minifying it:

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

Then encode your comment in binary:

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

Then steg your binary:

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

Here is your output:

$jsonWithComment = $steg . $jsonMin;
Irregularity answered 24/4, 2014 at 17:23 Comment(4)
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.Irregularity
For greater comment density, couldn't you encode your comment in ternary and use space, tab, and newline to steg it?Atkins
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.Calliper
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.Irregularity
S
26

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.

Shoebill answered 20/7, 2015 at 9:26 Comment(0)
P
23

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

Pacian answered 26/8, 2016 at 17:31 Comment(0)
M
17

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

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

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

var strip_json_comments = require('strip-json-comments')
var json = '{/*rainbows*/"unicorn":"cake"}';
JSON.parse(strip_json_comments(json));
//=> {unicorn: 'cake'}
Mirthless answered 27/11, 2014 at 11:39 Comment(3)
Note that the json is not a valid JSON anymore when it includes these propriety comments.Morris
In which context does strip-json-comments run? Node.js?Daukas
@PeterMortensen i tried for node.js. you can try whether works on client-side js.Mirthless
V
14

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

{

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

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

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

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

}
Vasya answered 29/10, 2013 at 10:30 Comment(4)
You've emulated an INI file structure in JSON. Please, put down your Golden Hammer.Nils
RFC says "The names within an object SHOULD be unique". Also see this person that is having an error parsing JSON like the above: #4912886Irregularity
If you're using a schema to validate the JSON, it may fail due to the extra fields.Allusive
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?Anthropolatry
B
12

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));
Bipolar answered 6/12, 2013 at 21:46 Comment(16)
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.Poynter
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.Bipolar
+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...Delineator
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.Bipolar
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.Gradate
@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...Kenwee
@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.Delineator
@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.Kenwee
@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.)Delineator
@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. ;-)Kenwee
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.Irregularity
Note that the regexp doesn't work with URLs: "url": "http:// ... (oops!). You definitely need a real "JSON+comments" parser to strip comments.Gabbie
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).Bilander
@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.Tutelary
@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.Poynter
@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.Tutelary
D
12

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

Decanal answered 29/12, 2015 at 5:12 Comment(2)
It's not JSON anymore if you extend the language in custom ways that require a special preprocessor to handle.Rush
@meagar There was JSON5 spec, which supported comments, among other things. But in the end it never became standard.Decanal
G
11

json specs doesn't support comments BUT you can work around the problem by writing your comment as keys, like this

{
  "// my own comment goes here":"",
  "key1":"value 1",

  "// another comment goes here":"",
  "key 2": "value 2 here"
}

this way we are using the comment texts as keys ensuring (almost) that they are unique and they will not break any parsers. if some of your comments are not unique just add random numbers at the end.

if you need to parse comments to do any processing like stripping them you can fill the comment values with text indicating that it is a comment , like so:

   {
  "// my own comment goes here" : "_comment",
  "key1":"value 1",

  "// another comment goes here" : "_comment",
  "key 2": "value 2 here"
} 
  

this way a parser can find all comments and process them.

Gardant answered 17/2, 2022 at 11:49 Comment(0)
P
10

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
Plugugly answered 6/11, 2019 at 13:43 Comment(2)
VS Code .jsonc FTW 🙌Saylor
JSON5 isn't the fifth version of JSON.Daukas
S
10

As the inventor of JSON said:

JSON does not have comments. A JSON encoder MUST NOT output comments. A JSON decoder MAY accept and ignore comments.

The utility includes a decoder that does allow "#"-style comments and so jq is one of several tools that can be used in conjunction with JSON-with-comments files, so long as such files are treated as "jq programs", rather than as JSON files. For example:

$ jq -ncf <(echo $'[1, # one\n2 ] # two') 
[1,2]

More importantly, jq can handle very large JSON-with-comments files as programs; this can be illustrated using a well-known JSON file:

$ ls -l JEOPARDY_QUESTIONS1.json
-rw-r--r--  2 xyzzy  staff  55554625 May 12  2016 JEOPARDY_QUESTIONS1.json

$ jq -nf JEOPARDY_QUESTIONS1.json | jq length
216930
Shipman answered 25/6, 2021 at 2:55 Comment(0)
U
9

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.

Unfavorable answered 28/11, 2013 at 13:48 Comment(6)
Just make sure your "notex" names don't conflict with any real fields. is the problem. This is not an arbitrary solution.Irregularity
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.Kenwee
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.Scenery
If you're using a schema to validate the JSON, it may fail due to the extra fields.Allusive
Some object unmarshallers (e.g. Jackson, under some configurations) throw exceptions on unknown fields.Dovap
How is this different from previous answers?Daukas
C
9

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

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

{
    // Rainbows
    "unicorn": /* ❤ */ "cake"
}
Corelative answered 3/7, 2014 at 5:6 Comment(1)
Might as well minify that JSON while you're at it. See @kyle-simpson's answer about JSON.minify.Gradate
R
9

The Pure answer is No.

But some editors and platforms use workarounds to add comments to JSON.

1. Today most editors have built-in options and extensions to add comments to JSON documents. (eg:- VS Code also has a JSON with Comments (jsonc) mode / VS Code also has nice extensions for that)

Link to activate jsonc mode in VsCode

2. Some platforms provide built-in ways to add comments (impure json). (eg:- In firebase, I can comment firebase.jsons for a while without issue.

    {
    "hosting": {
        "headers": [
            /*{
              "source": "*.html",
              "headers": [
                {
                  "key": "Content-Security-Policy",
                  "value": "default-src 'self' ..."
                }
              ]
            },*/
        ]
      }
    }

3. In your own JSON parsing method, you can set a predefined key name as a comment.

eg:-

     {
        "comment" : "This is a comment",
        "//" :  "This also comment",
        "name" : "This is a real value"
     }
Respecting answered 14/8, 2021 at 10:5 Comment(1)
using .jsonc extension for vs code is a great option for simple use casesPoltroonery
P
8

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",
}
Pharmaceutics answered 28/1, 2014 at 15:4 Comment(9)
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.Recusant
RFC says: "The names within an object SHOULD be unique". See this error reported at: #4912886Irregularity
Doing this is an invitation for creating JSON that blows up on you at some random point in the future.Gradate
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.Guanine
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.Hoban
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.Zeitler
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.Dermott
@toolbear JSON does not "blow up". The parser does. It is a doubtful solution. But not worse than adding "_comment". Maybe better than nothing.Urbanus
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)Hodgkin
H
8

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'.)

Hewart answered 23/1, 2019 at 14:15 Comment(1)
jsonc is nice, but unfortunately, you are restricted to // comments. When you need something else , you are kinda broken, too. #58554133Hibbs
Z
7

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.

Zennas answered 19/7, 2014 at 10:29 Comment(1)
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.Houseroom
T
7

I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability.

-- Douglas Crockford

I removed JSON from my dependencies because I saw Douglas Crockford made it uncommentable, a practice which had destroyed interoperability.

-- Me

Conclusion: USE YAML

Taxaceous answered 7/12, 2023 at 20:44 Comment(0)
O
6

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.

Ozmo answered 7/11, 2015 at 13:59 Comment(0)
O
6

Although JSON does not support comments, JSONC does.

Name your file with '.jsonc' extension and use a jsonc parser.
Sorry if this answer was too late.

jsonWithComments.jsonc

Example:

{
    // This is a comment!
    "something": "idk"

}

If this is unclear, I think the bot is weird. Please try before voting this question as unhelpful.

Outrelief answered 16/12, 2021 at 2:53 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Antibes
+1, I love your answer. And it is also implemented... eg. python has jsonc parser: pypi.org/project/jsonc-parser as does c/c++ have various: https://mcmap.net/q/33004/-c-c-json-parser-closed/36471724Conciseness
A
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.

Alumina answered 16/4, 2017 at 17:32 Comment(0)
K
4

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 */
}
Kindness answered 8/12, 2016 at 11:21 Comment(4)
{ what_if: "I happen to have /* slashes and asterisks */ in my data?" }Tomika
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".Tomika
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.Kindness
@Tomika I agree... this seems to work for many cases: json.replace(/("\/\/.*"|"\/\*(?:.|\n)*?")|(\/\/.*|\/\*(?:.|\n)*?\*\/)/g, "$1") regexr.com/3p39pSynod
A
4

*.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,'')
Ares answered 8/7, 2018 at 13:11 Comment(1)
What is a "jcomment"?Daukas
G
4

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.
});
Granulite answered 19/3, 2019 at 9:52 Comment(0)
C
4

Well at the time of writing, appsettings.json supports comments.

e.g. (sample courtesy of Microsoft)

{
  "Logging": {
    "LogLevel": { // All providers, LogLevel applies to all the enabled providers.
      "Default": "Error", // Default logging, Error and higher.
      "Microsoft": "Warning" // All Microsoft* categories, Warning and higher.
    },
    "Debug": { // Debug provider.
      "LogLevel": {
        "Default": "Information", // Overrides preceding LogLevel:Default setting.
        "Microsoft.Hosting": "Trace" // Debug:Microsoft.Hosting category.
      }
    },
    "EventSource": { // EventSource provider
      "LogLevel": {
        "Default": "Warning" // All categories of EventSource provider.
      }
    }
  }
}
Crossopterygian answered 28/11, 2021 at 1:20 Comment(0)
K
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!

Krebs answered 25/3, 2016 at 2:46 Comment(1)
solution category == 'transform through preproc'Technetium
D
2

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

{
    "https://schema.org/comment": "this is a comment"
}
Dipterous answered 11/2, 2016 at 18:41 Comment(0)
S
2

"JSON doesn't have any documentation for comments"

But you can try this method to add comments,

By Adding key-value pairs with comments and descriptions:

{
"key": "some value",
"comments":"this is a comment"
"description":"this is some description of the comment defined above"
}

Reason: Why does JSON file not allow comments(by default)?

Because comments are usually added to source code to describe lines of code. JSON is purely about the data format to send, Hence It is not feasible to add comments to Json.

Hope it helps.

Sex answered 26/3, 2023 at 12:31 Comment(1)
Why can't you use comments in JSON to describe the data? JSON is no longer used only for transmitting data, but also as config files.Brigittebriley
M
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.

Machicolation answered 2/7, 2015 at 19:48 Comment(0)
S
1

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

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

import json, re

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

print(parse_json("""
{
  // This is a comment
  "name": "value" // so is this
  // "name": "value"
  // the above line gets removed
}
"""))
Sparerib answered 6/4, 2019 at 8:38 Comment(0)
M
1

Yes. You can put comments in a JSON file.

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

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

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

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

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

Marry answered 12/6, 2020 at 6:43 Comment(8)
N.B. "The names within an object SHOULD be unique." (Source: IETF JSON Spec, December 2017Blackjack
SHOULD means something different to MUST in a spec. The other answers with comments will break every JSON parser out there. I'd be interested to know if duplicate keys has any bad side effects anywhere.Marry
My point (merely) was not that the names within an object MUST be unique, simply that they SHOULD be unique. After scouring Stack Overflow (and the wider web) for over a day, I have done my best to come up with my own approach.Blackjack
Ahh, that's an interesting approach... It requires custom logic to parse, and it moves the comments away from the thing it's describing... ?Marry
It requires a custom-written reader if you want to see the comments in the right place. Otherwise (ie. normally) there is simply a block of comments at the bottom of the JSON, at root level, with a reserved name, which can be safely ignored and left alone.Blackjack
When would you not want to see the comments in the right place?!Marry
Hey - I think we have a misunderstanding. I don't care about reading the comments in a parsed JSON object in Javascript. I want to 1) be able to read meaningful comments when I'm editing the source (ie NOT at runtime), and 2) I don't comments in my JSON to break standards compliant parsers.Marry
I've explained it badly. In the approach I've envisaged, comments are completely absent in any object parsed from the JSON. The comments are, nevertheless visible, in the right place, in a custom-reader (reader / writer / editor) in which you can read, write and edit the JSON file. (And in a non-custom reader, they sit in a block at the bottom of the JSON, out of the way of all of the data).Blackjack
D
1

I searched all pages of answers, and none mention this about JSON syntax highlighting on GitHub or on Stack Overflow, although this answer comes close.

Some JSON parsers accept C++-style comments. To trigger them when writing markdown on GitHub or Stack Overflow, for instance, you can specify the syntax highlighting type as jsonc. Example:

This:

```jsonc
// C++-style comment here
{
    "*.md": {
        "softwrap": true
    },
    "colorcolumn": 80,
    "savecursor": true,
    "scrollbar": true,
    "scrollspeed": 5,
    "softwrap": true,
    "wordwrap": true
}
```

Produces this:

// C++-style comment here
{
    "*.md": {
        "softwrap": true
    },
    "colorcolumn": 80,
    "savecursor": true,
    "scrollbar": true,
    "scrollspeed": 5,
    "softwrap": true,
    "wordwrap": true
}

As the answer I reference above mentions, you can then parse JSON which has C (/* */) and C++ (//) style comments using the amazing nlohmann json C++ library.

It is here: https://github.com/nlohmann/json

The single header file you need is here: https://github.com/nlohmann/json/blob/develop/include/nlohmann/json.hpp

That library says this: https://github.com/nlohmann/json#comments-in-json:

Comments in JSON

This library does not support comments by default. It does so for three reasons:

  1. Comments are not part of the JSON specification. You may argue that // or /* */ are allowed in JavaScript, but JSON is not JavaScript.
  2. This was not an oversight: Douglas Crockford wrote on this in May 2012:

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.

  1. It is dangerous for interoperability if some libraries would add comment support while others don't. Please check The Harmful Consequences of the Robustness Principle on this.

However, you can pass set parameter ignore_comments to true in the parse function to ignore // or /* */ comments. Comments will then be treated as whitespace.

ignore_comments is a bool and is the last parameter passed to the nlohmann::json::parse() function. See here: https://json.nlohmann.me/api/basic_json/parse/

References:

  1. https://gist.github.com/DamianEdwards/31d2457737304ca73556?permalink_comment_id=3574928#gistcomment-3574928
Dorm answered 25/1, 2023 at 6:13 Comment(0)
M
1

I think there is no such way. IDE says this too. It's just unsupported enter image description here

Maximilian answered 28/11, 2023 at 5:30 Comment(0)
P
0

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

"part_of_speech": {
  "__comment": [
    "@param {String} type - the following types can be used: ",
      "NOUN, VERB, ADVERB, ADJECTIVE, PRONOUN, PREPOSITION",
      "CONJUNCTION, INTERJECTION, NUMERAL, PARTICLE, PHRASE",
    "@param {String} type_free_form - is optional, can be empty string",
    "@param {String} description - is optional, can be empty string",
    "@param {String} source - is optional, can be empty string"
  ],
  "type": "NOUN",
  "type_free_form": "noun",
  "description": "",
  "source": "https://google.com",
  "noun_class": {
    "__comment": [
      "@param {String} noun_class - the following types can be used: ",
        "1_class, 2_class, 3_class, 4_class, 5_class, 6_class"
    ],
    "noun_class": "4_class"
  }
}
Paco answered 5/10, 2020 at 5:23 Comment(0)
V
0

As JSON codes look, It is mostly unnecessary to add comments inside, as you should make use of proper naming convention to make your keys name understandable and descriptive based on values you have to assign it.

I am not saying that comments in JSON is totally bad practice, But IMO, you should get it descriptive or consider it on the top of code as usual, instead of getting comments inside. Because it uglify our beautiful code.

"good-stuff" : {
  "descriptive-stuff1" : "I am understandable",
  "descriptive-stuff2" : [ "okay", "awesome" ]
}

Sorry for getting out of topic a little bit, Happy coding!

Velar answered 7/4 at 17:37 Comment(0)
K
-2

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

{
  // this is a comment for those who is ok with being different
  "regular-json": "stuff"...
}
Kirkkirkcaldy answered 10/3, 2021 at 18:9 Comment(4)
I think you should specify the proper syntax to provide a complete answer.Photogene
If there are JSON parsers out there that parse non-standard JSON, it doesn't mean that adding comments are allowed in JSON.Berwick
That you have a parser that does not follow the JSON spec does not mean it is a feature of JSON. You can work around the lack of comments in many ways, some of which have been mentioned here, including "// key" : "comment" that are within the spec, but still might fail if validating the json against a schema.Semipermeable
if it looks like a comment and works like a comment it is good enough for me to call it a comment. If you want a 100% pure definitions you should head to the maths website and discuss "dilemma of spherical knight in vacuum". thank youKirkkirkcaldy
I
-5

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);
Interject answered 7/7, 2014 at 20:8 Comment(7)
Your regexp would remove things like /*hey*/ even from inside strings.Somewise
Good catch! So just change some stuff on regex.Owen
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.Gradate
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.Rush
@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.htmlOwen
@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.Rush
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.Rush

© 2022 - 2024 — McMap. All rights reserved.