Can comments be used in JSON?

Multi tool use
Can comments be used in JSON?
Can I use comments inside a JSON file? If so, how?
If you, like me, were wondering whether
//comments
are OK for the specific use-case of a Sublime Text configuration file, the answer is yes (as of version 2). Sublime Text will not complain about it, at least, whereas it will complain about {"__comment": ...}
in the console, because it is an unexpected field.– hangtwenty
Feb 1 '13 at 15:12
//comments
{"__comment": ...}
and perhaps this is one reason why TOML was created..
– Alex Nolasco
May 1 '13 at 5:22
Slightly noobish but ,i also tried using // for comments in JSON. Now I realize it is strictly used for interchange/exchange. Sigh! I cant comment any more :(. Life is doomed!.
– Sid
Sep 25 '13 at 11:29
JSON5 supports comments: stackoverflow.com/a/7901053/108238
– schoetbi
Feb 2 '15 at 11:13
44 Answers
44
No.
The JSON should all be data, and if you include a comment, then it will be data too.
You could have a designated data element called "_comment"
(or something) that would be ignored by apps that use the JSON data.
"_comment"
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"
}
}
}
}
}
It might pay to have some kind of prefix on the actual comment in case there's ever a valid field named comment:
"__comment":"comment text goes here...",
– Rob Fonseca-Ensor
Feb 3 '10 at 11:41
"__comment":"comment text goes here...",
A fairly recent explanation/rationale for why there are no comments in JSON (or more accurately, why they were removed early on): plus.google.com/118095276221607585885/posts/RK8qyGVaGSr Also see, tech.groups.yahoo.com/group/json/message/156 and other discussion in that thread.
– Michael Burr
Jun 28 '12 at 22:14
BTW, the json library for Java google-gson has support for comments.
– centic
Oct 1 '12 at 12:21
What about if I wanted a separate comment on the
Accronym
and Abbrev
properties? I've used this pattern before but stopped since it doesn't allow me to do that. It is a hack. Maybe if I prepend a property name with __comment__
instead. That is "__comment__Abbrev", still a hack, but would let me comment on all prpoerties– Juan Mendes
Aug 11 '14 at 12:58
Accronym
Abbrev
__comment__
you could also use "//": this looks more native and is still repeatable in the same parent
– smnbbrv
Aug 28 '15 at 9:59
No, comments of the form //…
or /*…*/
are not allowed in JSON. This answer is based on:
//…
/*…*/
application/json
If you'd like to annotate your JSON with comments (thus making it invalid JSON), then minify it before parsing or transmitting. Crockford himself acknowledged this in 2012 in the context of configuration files.
– toolbear
Aug 7 '14 at 19:26
@alkuzad: When it comes to formal grammars, there must be something that explicitly says that they are allowed, not the other way around. For instance, take your programming language of choice: Just because some desired (but missing) feature isn't explicitly disallowed, doesn't mean that your compiler will magically recognize it.
– stakx
Sep 28 '15 at 7:01
Yes. The JSON format has a lot of dead-space between elements and is space-insensitive in those regions, so there's no reason why you can't have single or multi-line comments there. Many parsers and minifiers support JSON comments as well, so just make sure your parser supports them. JSON is used a lot for application data and configuration settings, so comments are necessary now. The "official spec" is a nice idea, but it's insufficient and obsolete, so too bad. Minify your JSON if you're concerned about payload size or performance.
– Triynko
Oct 31 '17 at 17:36
Although your answer is absolutely correct, it should be said that this is BS. With so many end users coming across the need for json configuration, then comments are exceedingly helpful. Just because some tin-foil hats decided that JSON is and must always be machine readable, ignoring the fact that humans needs to read it to, is imho a travesty of small mindedness.
– cmroanirgo
Jan 21 at 0:29
@cmroanirgo: You're obviously not the first to complain about that limitation of JSON... that's why we have parsers that silently allow comments, and other formats such as YAML and JSON5. However this doesn't change the fact that JSON is what it is. Rather, I find it interesting that people started using JSON for purposes where it clearly wasn't sufficient in the first place, given the limitation in question. Don't blame the JSON format; blame ourselves for insisting on using it where it isn't a particularly good fit.
– stakx
Jan 21 at 7:48
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.
The only problem I have with JSON.minify() is that it is really really slow. So I made my own implementation that does the same thing: gist.github.com/1170297 . On some large test files your implementation takes 74 seconds and mine 0.06 seconds.
– WizKid
Aug 25 '11 at 9:16
it'd be great if you could submit the suggested alternative algorithm to the github repo for JSON.minify(), so that it can be ported to all the supported langs: github.com/getify/json.minify
– Kyle Simpson
Aug 30 '11 at 17:20
@MiniGod I have already heard Doug's thoughts on this topic many times. I addressed them long ago in my blog post: blog.getify.com/json-comments
– Kyle Simpson
Feb 26 '13 at 23:21
@MarnenLaibow-Koser there are still valid uses for comments even for data stream (or even packet) usage: inclusion of diagnostics metadata like creation time or sources is common use with XML, and perfectly sensible for JSON data as well. Arguments against comments are shallow, and any textual data format should allow for comments, regardless of implied intended usage (nothing spec suggest JSON can not be used elsewhere, fwiw)
– StaxMan
Mar 28 '14 at 22:09
If JSON is to have universal acceptance (which it basically does) then it should have universal application. Example: JSON can serve as an application configuration file. This application would desire comments.
– eggmatters
Jan 27 '16 at 19:31
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+
I thought JSON was to supposed to be more human readable than, say, XML? Comments are for readability.
– intrepidis
Oct 14 '12 at 13:00
Anyway, you could be naughty and add parsing directives in the JSON: {"__directives":{"#n#":"DateTime.Now"}, "validdate":"#n#"}... It looks like YAML is the way forward then...
– intrepidis
Oct 14 '12 at 13:04
Personal opinion: not allowing comments IS lame. I had no option other than building a non-standard JSON parser that ignores comments, to decode my config files.
– caiosm1005
Sep 23 '13 at 2:28
@ArturCzajka I still dislike the fact JSON doesn't support comments, but I gave INI a try and I must admit it makes much more sense to use them over JSON for config files. Thanks for the response and hopefully more people will change their minds as they read this conversation. (making a parser was more of an exercise anyway :)
– caiosm1005
Oct 4 '13 at 2:42
That's like requiring all bicycles to have training wheels because some people can't ride bicycles. Removing an important feature because stupid people abuse it is bad design. A data format should prioritize usability over being idiot-proof.
– Phil Goetz
May 14 '15 at 17:24
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!
From the specification: The names within an object SHOULD be unique.
– Quentin
Aug 2 '13 at 13:50
"all the implementations handle it the same" — That's a difficult thing to prove.
– Quentin
Aug 2 '13 at 14:20
The order of elements in JSON is not guaranteed. That means the "last" item could change!
– sep332
Aug 2 '13 at 14:33
This clearly violates the spec (see above comments), don't do this. ietf.org/rfc/rfc4627.txt?number=4627
– voidlogic
Aug 2 '13 at 14:39
NO - what if the parser is streaming? What if the parser reads it into a dictionary where key ordering is undefined? kill this with fire.
– deanWombourne
Aug 2 '13 at 14:55
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.
See hjson.org for JavaScript, Java, Python, PHP, Rust, Go, Ruby and C# libraries.
Upvoted. It's obviously a good variation un-open conservative people would just love to hate. I hope your implementation gets known further - and perhaps even gets more popular than the original ;) I hope someone gets to implement it with Ruby as well. @adelphus The language being well-defined is your own perspective or opinion. Being a conservative "developer" if you are one doesn't prove that you are better and you could be even worse keeping yourself locked up in limited spaces. Don't go judging people as terrible developers easily.
– konsolebox
Jun 30 '14 at 19:20
Sorry about that, @konsolebox. Perhaps you might reconsider your "well-defined JSON is your opinion" view after reading ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf It is a real standard and devs implementing their own "special" versions leads to fragmentation, confusion and a lot of wasted time. Look at the mess web developers are left with when writing code just because each browser implements slightly different versions of standards. The JSON language may not be perfect, but fragmentation is worse. And yes, that's just a opinion and you're free to disagree.
– adelphus
Jul 9 '14 at 16:02
I admire your gumption, but you're kinda re-inventing YAML. If you want lot's of flexibility and human readability, use YAML (don't actually: stackoverflow.com/questions/450399/…) or stick with curmudgeony, yet unambiguous JSON.
– toolbear
Aug 7 '14 at 18:25
I find the most user-friendly configuration format is still INI. It's straightforward and not very syntax heavy. This makes it less intimidating for users just dipping their toes in the configuration pond.
– Matt
Feb 10 '15 at 15:15
Whenever you need json as config (where comments are needed) - name your file ".js" instead of ".json".. js can of course handle any valid json object and additionally can handle comments.. That's the reason why it is "webpack.config.js" and not "webpack.config.json" (well there's a lot more reasons for that too in webpack :P)
– jebbie
Apr 6 '16 at 14:20
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.
Consider using YAML. It's nearly a superset of JSON (virtually all valid JSON is valid YAML) and it allows comments.
@g33kz0r Correct, hence my description of YAML as a near-superset of JSON.
– Marnen Laibow-Koser
Sep 12 '12 at 14:58
@NateS Many people had already pointed out that the answer was no. I suggested a better way to achieve the OP's goal. That's an answer.
– Marnen Laibow-Koser
Mar 28 '14 at 12:57
Downside:
yaml
library isn't shipped with Python.– Bleeding Fingers
Apr 15 '14 at 10:06
yaml
@BleedingFingers So install it...
– Marnen Laibow-Koser
Apr 15 '14 at 16:19
@marnen-laibow-koser: yup, it must have been incompetence to use the available YAML libraries for Java and Perl and expect the YAML produced by each to be consumed by the other without error. That YAML interop was an issue, but JSON interop wasn't, is entirely explained by my lack of knowledge.
– toolbear
Aug 17 '14 at 23:32
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.
Is JSON schema alive? It exists but is it supported by any known library?
– Munhitsu
Oct 29 '12 at 14:31
yes, the json-schema google group is fairly active and I would recommend JSV for a good JavaScript implementation of a JSON Schema validator.
– raffel
Nov 27 '12 at 11:34
This only helps with structured documentation, not ad-hoc documentation
– Juan Mendes
Apr 4 '13 at 17:47
If you use clojure (and I'm sure you don't) there's a reasonably featured open-source JSON schema parser here: github.com/bigmlcom/closchema
– charleslparker
Apr 15 '13 at 13:50
@Munhitsu Manatee.Json (.Net) extensively supports JSON schema.
– gregsdennis
Jun 26 '15 at 0:26
If you are using Jackson as your JSON parser then this is how you enable it to allow comments:
ObjectMapper mapper = new ObjectMapper().configure(Feature.ALLOW_COMMENTS, true);
Then you can have comments like this:
{
key: "value" // comment
}
And you can also have comments starting with #
by setting:
#
mapper.configure(Feature.ALLOW_YAML_COMMENTS, true);
But in general (as answered before) the spec does not allow comments.
Opening that link timed out when I tried it:
The connection to the server was reset while the page was loading.
– Peter Mortensen
Jan 19 '17 at 18:14
The connection to the server was reset while the page was loading.
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.
Groovy has some built-in classes for handling JSON. JsonSlurper can handle comments. Of course, comments are not allowed in the official spec, so this behavior in any parser is non-standard and non-portable.
– izrik
Nov 6 '15 at 21:47
Sorry, we can't use comments in JSON... See the syntax diagram for JSON on JSON.org.
Douglas Crockford says "why he removed comments in JSON and providing an alternative way to do that":
I removed comments from JSON because I saw people were using them to
hold parsing directives, a practice which would have destroyed
interoperability. I know that the lack of comments makes some people
sad, but it shouldn't.
Suppose you are using JSON to keep configuration files, which you
would like to annotate. Go ahead and insert all the comments you like.
Then pipe it through JSMin before handing it to your JSON parser.
I believe what you are referring to is just text annotation for documentation purpose. It's not what is actually returned by the web service.
– HoLyVieR
Nov 18 '12 at 3:56
Crockford later went on to write: "Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser." See @kyle-simpson's answer about JSON.minify for more info.
– toolbear
Aug 7 '14 at 19:22
This answer duplicates @ArturCzajka who posted the same quote a year before.
– kenorb
Sep 2 '16 at 12:17
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.
Probably the best suggestion so far, though still an issue for keeping files as an interchange format, as they need pre-processing before use.
– Orbling
Feb 25 '11 at 11:04
I agree and have written a JSON parser in Java, available at www.SoftwareMonkey.org, that does exactly that.
– Lawrence Dol
Jul 28 '12 at 1:51
Despite I think, it is not a good idea to extend JSON (without calling it a different exchange format): make sure to ignore "comments" within strings. { "foo": "/* This is not a comment.*/" }
– stofl
Jul 27 '13 at 12:09
"...would be a one liner" umm, no, actually, JSON is not a regular grammar where a regular expression can simply find matching pairs of /*. You have to parse the file to find if a /* appears inside a string (and ignore it), or if it's escaped (and ignore it), etc. Also, your answer is unhelpful because you simply speculate (incorrectly) rather than providing any solution.
– Kyle Simpson
Dec 8 '13 at 21:55
What @kyle-simpson said. Also, he's too modest to direct readers to his own answer about using JSON.minify as an alternative to ad hoc regexps. Do that, not this.
– toolbear
Aug 7 '14 at 19:32
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"
}
FYI, Firebase Realtime Database does not allow the use of '/' in a key. so this can be a nice convention for your own use, but you cannot do it in Firebase
– gutte
Nov 1 '17 at 20:44
This method breaks some libraries, which require that the key must be unique. I'm working around that issue by numbering the comments.
– MovGP0
Jan 19 at 11:45
good comment, I found this question on SO ... this part seems not to be covered by the spec stackoverflow.com/questions/21832701/…
– mana
Jan 20 at 19:36
I guess //1 //2 //3 would work.
– ggb667
Feb 21 at 14:44
I tend to use it like this nowadays: { "//foo": "foo comment", "foo": "foo value", "//bar": "bar comment", "bar": "bar value" } You can use an array for multiple comments: { "//foo": [ "foo comment 1", "foo comment 2" ], "foo": ''foo value" }
– MovGP0
Mar 9 at 16:29
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.
It is hard to understand why someone would have problem with stating a fact.
– dvdmn
Jul 29 '14 at 14:17
I would assume someone took exception because the above is no longer JSON, or is invalid JSON. Perhaps adding a short disclaimer would appease.
– toolbear
Aug 7 '14 at 18:12
I completely agree with you, and yet there are 883 upvotes so far for the non-answer that just states the obvious. Ideological purity valued above helpful information, that's SO for you.
– John
Aug 20 '14 at 16:48
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.
It is true that JSON format does not have comments. Personally I think that is a significant mistake -- ability to have comments as metadata (not data) is a very useful thing with xml. Earlier draft versions of JSON specification did include comments, but for some reason they were dropped. :-/
– StaxMan
Sep 1 '09 at 18:20
@StaxMan they were dropped exactly because people started using them as metadata. Crockford said it breaked the compatibility for what the format was designed, and I agree: if you want metadata, why not include it as actual data? It's even easier to parse this way.
– Camilo Martin
Dec 11 '10 at 9:03
Metadata belongs in metadata constructs (e.g. HTML <meta> tags), not comments. Abusing comments for metadata is just a hack used where no true metadata construct exists.
– Marnen Laibow-Koser
Sep 6 '11 at 4:55
That's exactly the reason why it was dropped: comments used as metadata would break interoperability. You should just store your meta-data as JSON too.
– gaborous
Jun 25 '13 at 14:50
This answer is redundant with better written, higher upvoted answers, that say essentially the same thing, even though this may have been written earlier. Cest la vie.
– toolbear
Aug 7 '14 at 19:35
It depends on your JSON library. Json.NET supports JavaScript-style comments, /* commment */
.
/* commment */
See another Stack Overflow question.
And I believe that is why I see a comment in a screenshot on this ASP.NET vNext preview page (under package.json): blogs.msdn.com/b/webdev/archive/2014/06/03/… although I haven't found anything in the spec yet.
– webXL
Sep 17 '14 at 21:54
JSON does not support comments natively, but you can make your own decoder or at least preprocessor to strip out comments, that's perfectly fine (as long as you just ignore comments and don't use them to guide how your application should process the JSON data).
JSON does not have comments. A JSON encoder MUST NOT output comments.
A JSON decoder MAY accept and ignore comments.
Comments should never be used to transmit anything meaningful. That is
what JSON is for.
Cf: Douglas Crockford, author of JSON spec.
Crockford later went on to write: "Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser." See @kyle-simpson's answer about JSON.minify for more info.
– toolbear
Aug 7 '14 at 19:14
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.
"#": "comment"
For config files, I'd suggest YAML, not JSON. It's (almost) a more powerful superset of JSON, but supports more readable constructs as well, including comments.
– Marnen Laibow-Koser
Oct 19 '11 at 21:35
how many languages do you think supports YAML out of the box compared to json ?
– momo
Jan 13 '12 at 13:26
@Hamidam Over a dozen languages support yaml: yaml.org - but you're right to ask how many have support built-in, without the need for a third-party library dependency. Looks like Ruby 1.9.2 does. Anyone know of others? And which languages ship support for json by default?
– nealmcb
Mar 21 '12 at 15:53
YAML interop is a lie: stackoverflow.com/questions/450399/… . If your instinct is to use JSON for configuration files, follow it.
– toolbear
Aug 7 '14 at 19:10
This is old, but I believe that using # is not a good idea. Json is close to the syntax of a Javascript litteral. Javascript supports 2 types of comment : // and /* ... */ If I were you I would stick with one or both these types of comments.
– Pascal Ganaye
Dec 2 '15 at 18:24
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-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!
No need to fragment JSON. JSON with comments is no longer JSON. But it's perfectly acceptable to annotate your JSON with comments, so long as you make sure to strip them out before parsing or transmitting it. It should never be the receiver's responsibility to do this.
– toolbear
Aug 7 '14 at 19:19
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.
/* */
dojo.xhrGet()
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.
No. Not this. JSON doesn't have comments. If you choose to annotate your JSON with comments, minify it before parsing or transmitting. This shouldn't be the receiver's responsibility.
– toolbear
Aug 7 '14 at 19:31
I didn't say that JSON has comments. Neither did I mean to imply that it's appropriate to include them in your JSON, especially in a production system. I said that the Dojo toolkit permits you to add them, which is (or at least, was) factually true. There are very helpful use-cases out there for doing so in your testing phase.
– David
Aug 7 '14 at 23:37
It's bad voodoo to serve up commented, and thus invalid JSON, which
dojo.xhrGet()
implicitly encourages by accepting.– toolbear
Aug 8 '14 at 20:21
dojo.xhrGet()
I still vote for upgrading the JSON spec to allow comments. I'm all for minifying and stripping the comments before transmitting the JSON, but not having any ability to comment your JSON in any standard way without having to pass it through a separate utility before parsing it just seems silly. I also makes it impossible to use a JSON editor on your JSON configuration files, because your files are not valid JSON.
– Craig
Sep 15 '14 at 7:03
You can have comments in JSONP, but not in pure JSON. I've just spent an hour trying to make my program work with this example from Highcharts: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
If you follow the link, you will see
?(/* AAPL historical OHLC data from the Google Finance API */
[
/* May 2006 */
[1147651200000,67.79],
[1147737600000,64.98],
...
[1368057600000,456.77],
[1368144000000,452.97]
]);
Since I had a similar file in my local folder, there were no issues with the Same-origin policy, so I decided to use pure JSON... and, of course, $.getJSON
was failing silently because of the comments.
$.getJSON
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.
text/javascript
application/json
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.
Could you please add an example? Then you may actually need those extra characters.
– dgilperez
Dec 17 '15 at 0:15
It's required by the SO guidelines to provide an actual answer. Link-only answers are not desired. You can check the guidelines stackoverflow.com/help/how-to-answer
– dgilperez
Dec 29 '15 at 20:06
SO is moderated by its users. That means I can provide an answer if I have it the same way I can comment yours if it doesn't follow guidelines. That's how SO gets to be a great resource.
– dgilperez
Dec 30 '15 at 11:21
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.
_comment
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;
The RFC only states "whitespace is allowed before or after any of the six structural characters", not explicitly mentioning strings, numbers, "false", "true", "null". This omission is ignored in ALL implementations.
– William Entriken
Sep 24 '14 at 18:15
Yes. This is an abuse of the RFC not envisioned by its author. You can accept that without flagging and modding my comments/answer to oblivion.
– William Entriken
Jan 4 at 18:44
There is a good solution (hack), which is valid JSON.
Just make the same key twice (or more). For example:
{
"param" : "This is the comment place",
"param" : "This is value place",
}
So JSON will understand this as:
{
"param" : "This is value place",
}
This method may cause some troubles if anybody will loop through the object. On the first iteration the program will have no information that the entry is a comment.
– user2073253
Feb 12 '14 at 20:24
RFC says: "The names within an object SHOULD be unique". See this error reported at: stackoverflow.com/questions/4912386/…
– William Entriken
Jun 10 '14 at 15:59
Doing this is an invitation for creating JSON that blows up on you at some random point in the future.
– toolbear
Aug 7 '14 at 19:00
There is no guarantee that order matters in the list of object name/value pairs. A parser could parse them "out of order" and then this is broken.
– Mark Lakata
May 26 '15 at 22:26
Behaviour of a JSON parser with this kind of code is undefined. There is nothing to say that the parser behaves as if only the last value was present. It could behave as if only the first value was present, or any value, or as if the value was an array.
– gnasher729
Oct 6 '17 at 18:24
We are using strip-json-comments
for our project. It supports something like:
strip-json-comments
/*
* Description
*/
{
// rainbows
"unicorn": /* ❤ */ "cake"
}
Simply npm install --save strip-json-comments
to install and use it like:
npm install --save strip-json-comments
var strip_json_comments = require('strip-json-comments')
var json = '{/*rainbows*/"unicorn":"cake"}';
JSON.parse(strip_json_comments(json));
//=> {unicorn: 'cake'}
To cut a JSON item into parts I add "dummy comment" lines:
{
"#############################" : "Part1",
"data1" : "value1",
"data2" : "value2",
"#############################" : "Part2",
"data4" : "value3",
"data3" : "value4"
}
You've emulated an INI file structure in JSON. Please, put down your Golden Hammer.
– Artur Czajka
Nov 18 '13 at 16:53
RFC says "The names within an object SHOULD be unique". Also see this person that is having an error parsing JSON like the above: stackoverflow.com/questions/4912386/…
– William Entriken
Jun 10 '14 at 15:58
If you're using a schema to validate the JSON, it may fail due to the extra fields.
– gregsdennis
Jun 26 '15 at 0:32
If you're really determined to add comments to your JSON, it would make much more sense to do something like this:
{ "comment-001":"This is where you do abc...", "comment-002":"This is where you do xyz..." }
This keeps the name unique and lets you add whatever string value you like. It's still a kludge, because comments should not be part of your JSON. As another alternative, why not add comments before or after your JSON, but not within it?– Jazimov
Sep 4 '15 at 22:51
{ "comment-001":"This is where you do abc...", "comment-002":"This is where you do xyz..." }
The author of JSON wants us to include comments in the JSON, but strip them out before parsing them (see link provided by Michael Burr.) If JSON should have comments, why not standardize them, and let the JSON parser do the job? I don't agree with the logic there, but, alas, that's the standard. Using YAML solution as suggested by others is good, but requires library dependency.
If you want to strip out comments, but don't want to have a library dependency, here is a two-line solution, which works for C++-style comments, but can be adapted to others:
var comments=new RegExp("//.*", 'mg');
data = JSON.parse(fs.readFileSync(sample_file, 'utf8').replace(comments, ''));
Note that this solution can only be used in cases where you can be sure that the JSON data does not contain the comment initiator, e.g. ('//').
Another way to achieve JSON parsing, stripping of comments, and no extra library, is to evaluate the JSON in a JS interpreter. The caveat with that approach, of course, is that you would only want to evaluate untainted data (no untrusted user-input.) Here is an example of this approach in node.js -- another caveat, following example will only read the data once and then it will be cached:
data = require(fs.realpathSync(doctree_fp));
This does not work, because it doesn't take into account if /* could be escaped, or could be inside a string literal. JSON is not a regular grammar and thus regular expressions are not enough. You have to parse it to find out where the comments are.
– Kyle Simpson
Dec 8 '13 at 21:58
It will work in limited situations where you can be sure that your JSON does not contain any data with the comment string in it. Thank you for pointing out that limitation. I have edited the post.
– Joshua Richardson
Dec 11 '13 at 23:52
+1 for the link! Actually I think it is a good thing that comments are not supported because when sending data between a client and server, comments are definitively useless and pump lots of bandwidth for nothing. It's like someone who would ask to have comments in an MP3 structure or a JPEG data block...
– Alexis Wilke
Jun 26 '14 at 8:45
Thanks for the +1! You have to remember that JSON is used for much more than server/client communication. Also, depending upon your data size, and packet size, sending comments may not increase your bandwidth at all, and it could be useful for your client to have access to the extra context, and you could always have the server strip the comments if you didn't want to send them over the wire.
– Joshua Richardson
Jun 27 '14 at 3:13
What @kyle-simpson said. Also, he's too modest to direct readers to his own answer about using JSON.minify as an alternative to ad hoc regexps. Do that, not this.
– toolbear
Aug 7 '14 at 19:06
You can use JSON with comments in it, if you load it as a text file, and then remove comments from it.
You can use decomment library for that. Below is a complete example.
Input JSON (file input.js):
/*
* multi-line comments
**/
{
"value": 123 // one-line comment
}
Test Application:
var decomment = require('decomment');
var fs = require('fs');
fs.readFile('input.js', 'utf8', function (err, data) {
if (err) {
console.log(err);
} else {
var text = decomment(data); // removing comments
var json = JSON.parse(text); // parsing JSON
console.log(json);
}
});
Output:
{ value: 123 }
See also: gulp-decomment, grunt-decomment
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
@StingyJack: To explain things that may not be obvious, or whatever else one might do with comments. I for one often have comments in data files. XML, ini files, and many other formats include provisions for comments.
– Michael Burr
Oct 28 '08 at 20:51