标签云

微信群

扫码加入我们

WeChat QR Code

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


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.

2018年07月23日24分58秒

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.

2018年07月24日24分58秒

and perhaps this is one reason why TOML was created..

2018年07月23日24分58秒

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!.

2018年07月23日24分58秒

JSON5 supports comments: stackoverflow.com/a/7901053/108238

2018年07月23日24分58秒

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...",

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

BTW, the json library for Java google-gson has support for comments.

2018年07月23日24分58秒

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

2018年07月23日24分58秒

you could also use "//": this looks more native and is still repeatable in the same parent

2018年07月23日24分58秒

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.

2018年07月24日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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

2018年07月23日24分58秒

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

2018年07月23日24分58秒

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)

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

I thought JSON was to supposed to be more human readable than, say, XML? Comments are for readability.

2018年07月23日24分58秒

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

2018年07月24日24分58秒

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.

2018年07月23日24分58秒

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 :)

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

From the specification: The names within an object SHOULD be unique.

2018年07月23日24分58秒

"all the implementations handle it the same" — That's a difficult thing to prove.

2018年07月23日24分58秒

The order of elements in JSON is not guaranteed. That means the "last" item could change!

2018年07月23日24分58秒

This clearly violates the spec (see above comments), don't do this. ietf.org/rfc/rfc4627.txt?number=4627

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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)

2018年07月23日24分58秒

g33kz0r Correct, hence my description of YAML as a near-superset of JSON.

2018年07月23日24分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.

2018年07月23日24分58秒

Downside: yaml library isn't shipped with Python.

2018年07月23日24分58秒

BleedingFingers So install it...

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

Is JSON schema alive? It exists but is it supported by any known library?

2018年07月23日24分58秒

yes, the json-schema google group is fairly active and I would recommend JSV for a good JavaScript implementation of a JSON Schema validator.

2018年07月23日24分58秒

This only helps with structured documentation, not ad-hoc documentation

2018年07月23日24分58秒

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

2018年07月24日24分58秒

Munhitsu Manatee.Json (.Net) extensively supports JSON schema.

2018年07月23日24分58秒

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

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

This answer duplicates ArturCzajka who posted the same quote a year before.

2018年07月23日24分58秒

Probably the best suggestion so far, though still an issue for keeping files as an interchange format, as they need pre-processing before use.

2018年07月23日24分58秒

I agree and have written a JSON parser in Java, available at www.SoftwareMonkey.org, that does exactly that.

2018年07月23日24分58秒

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.*/" }

2018年07月23日24分58秒

"...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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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

2018年07月23日24分58秒

This method breaks some libraries, which require that the key must be unique. I'm working around that issue by numbering the comments.

2018年07月23日24分58秒

good comment, I found this question on SO ... this part seems not to be covered by the spec stackoverflow.com/questions/21832701/…

2018年07月23日24分58秒

I guess //1 //2 //3 would work.

2018年07月23日24分58秒

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

2018年07月23日24分58秒

It is hard to understand why someone would have problem with stating a fact.

2018年07月23日24分58秒

I would assume someone took exception because the above is no longer JSON, or is invalid JSON. Perhaps adding a short disclaimer would appease.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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. :-/

2018年07月23日24分58秒

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.

2018年07月24日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

how many languages do you think supports YAML out of the box compared to json ?

2018年07月23日24分58秒

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?

2018年07月23日24分58秒

YAML interop is a lie: stackoverflow.com/questions/450399/… . If your instinct is to use JSON for configuration files, follow it.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

It's bad voodoo to serve up commented, and thus invalid JSON, which dojo.xhrGet() implicitly encourages by accepting.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

Could you please add an example? Then you may actually need those extra characters.

2018年07月23日24分58秒

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

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

RFC says: "The names within an object SHOULD be unique". See this error reported at: stackoverflow.com/questions/4912386/…

2018年07月23日24分58秒

Doing this is an invitation for creating JSON that blows up on you at some random point in the future.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

You've emulated an INI file structure in JSON. Please, put down your Golden Hammer.

2018年07月23日24分58秒

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/…

2018年07月23日24分58秒

If you're using a schema to validate the JSON, it may fail due to the extra fields.

2018年07月24日24分58秒

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?

2018年07月24日24分58秒

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.

2018年07月23日24分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.

2018年07月24日24分58秒

+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...

2018年07月23日24分58秒

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.

2018年07月23日24分58秒

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.

2018年07月23日24分58秒