Can comments be used in JSON?

6 075


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

Michael Gundlach

Posted 2008-10-28T20:39:03.333

Reputation: 35 712

116@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 – 2008-10-28T20:51:29.377

15If 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 – 2013-02-01T15:12:22.040

3and perhaps this is one reason why TOML was created.. – Alex Nolasco – 2013-05-01T05:22:12.277

8Slightly 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 – 2013-09-25T11:29:39.753

Check out and you will see comments. This is JSONP, though, not pure JSON. See my response below.

– osa – 2013-10-07T20:39:35.327

@fonzo-highway Change your username and the next will ask "Who is fonzo-highway?" :o) – Sir Rufo – 2014-10-31T10:11:03.857

@DavePeck I'd say that's a good time to get started on an Objective-C binding for YAML and forget all the cruft you used to have to type to manually write JSON. – None – 2014-12-28T18:40:48.083


JSON5 supports comments:

– schoetbi – 2015-02-02T11:13:53.380

Ruby's json parser is another example of a parser that supports comments. – Ben Crowell – 2016-06-20T17:21:01.500

I dont understand why anyone would ever need that – Tom Doodler – 2016-08-08T07:22:48.033


If you want a language for configuration with comments see TOML

– schoetbi – 2016-09-12T13:20:35.963

1Comments are not permitted because it's too late to support comments. Major oversight. Ironically, YAML supports comments. – bvj – 2017-08-02T07:08:02.783 has 2 ways to do add a comment functionality to your JSON file – Flotolk – 2018-01-08T19:32:15.290

2I would love to know what I wrote 10 years ago to get a 96 upvote correction statement. I didn't think I started to even use JSON until about 2 years ago. – StingyJack – 2018-04-02T22:54:54.797

here is a nice trick

– osama yaccoub – 2018-04-04T15:48:26.340

1This is why YAML is superior. – Chloe – 2018-07-17T17:07:45.377

Look up RFC 4627 and related. – MikeW – 2018-10-29T10:29:30.743


4 276


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.

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"


Posted 2008-10-28T20:39:03.333

Reputation: 57 572


A fairly recent explanation/rationale for why there are no comments in JSON (or more accurately, why they were removed early on): Also see, and other discussion in that thread.

– Michael Burr – 2012-06-28T22:14:25.763


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

– centic – 2012-10-01T12:21:44.237

159It 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 – 2010-02-03T11:41:45.247

9What 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 "commentAbbrev", still a hack, but would let me comment on all prpoerties – Juan Mendes – 2014-08-11T12:58:25.797

@JuanMendes: you are allowed to have the same key multiple times. – progo – 2014-12-17T07:03:58.317

We can to select more unique comment keys format for this. Something like {"<!-- glossary -->": "Comment text"} looks ok. "/* glossary */" too. – vp_arth – 2014-12-19T04:21:00.537

Why is GlossList not an array (GlossList: [ { .. }, { .. } ])? – Luca Steeb – 2015-05-12T12:58:11.863

If you're using a schema to validate the JSON, it may fail due to the extra fields. – gregsdennis – 2015-06-26T00:31:20.593

23you could also use "//": this looks more native and is still repeatable in the same parent – smnbbrv – 2015-08-28T09:59:50.697

1@JuanMendes Probably far too late to be of help, but for multi-line comments, make the value of the comment element an array of strings: [ "line 1", <CRLF> "line 2", <CRLF> "line 3" ]. – TripeHound – 2015-10-09T14:11:01.833

1The thing is it changes the semantic of the JSON, e.g. changing the length of an array. – Elgs Qian Chen – 2015-12-21T12:21:04.103

1When 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. – Петър Петров – 2016-02-27T13:59:59.833

There is JSON5 (5 referring to ECMAScript 5 (and later)).

– Peter Mortensen – 2017-01-19T18:42:29.310

There are a number of libraries and frameworks that now support comments in JSON files. In C# land, Newtonsoft's JSON.Net supports them, and as a result you'll observe comments used in various JSON's throughout .Net Core configuration files. – Ken Mason – 2017-08-14T18:48:13.847

If you are returning the json via api then the client should be using the HTTP Options verb to read the json descriptions/comments – MIKE – 2017-09-07T17:41:36.237

1XML wants its document back. – jwg – 2018-02-19T17:02:31.613

Yea you can try to use {"//": "Your comment"} – danger89 – 2018-03-20T19:12:48.180

But be careful! Some fully parsing engines need something as @JsonIgnoreProperties annotation, or else they will see unknown field as an error. – Gangnus – 2018-05-15T05:08:40.773

Just capturing a relevant excerpt from the first link that @MichaelBurr provided (the second is seemingly irretrievable): "Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser."--Douglas Crockford – chb – 2018-09-17T00:45:34.593

One of the links in my June 2012 comment no longer works. Another reader (@douglasgross) has provided this current link:

– Michael Burr – 2018-09-27T22:20:49.113

Thanks for the answer! As I was writing JSON scripts , I thought of adding a normal comment (//) , VSCode's Jslint immidiately highlighted the comment with a red line, saying "Comments are not permitted inJSON" – Imran Rafiq Rather – 2018-10-29T07:07:05.480

@danger89 you could, but this changes the length of the array. However, I see do see this used in tutorials where the code isn't going to be used in production – Pranav A. – 2018-11-24T22:44:55.263

1 606

No, comments of the form //… or /*…*/ are not allowed in JSON. This answer is based on:

  • RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON)
  • RFC 7159 The JavaScript Object Notation (JSON) Data Interchange Format - Obsoletes: 4627, 7158


Posted 2008-10-28T20:39:03.333

Reputation: 62 823

52If 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 – 2014-08-07T19:26:35.983

22@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 – 2015-09-28T07:01:23.910

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 – 2017-10-31T17:36:52.243

14Although 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 – 2018-01-21T00:29:27.690

3@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 – 2018-01-21T07:48:27.847


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:


When I released it, I got a huge backlash of people disagreeing with even the idea of it, so I decided that I'd write a comprehensive blog post on why comments make sense in JSON. It includes this notable comment from the creator of JSON:

Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser. - Douglas Crockford, 2012

Hopefully that's helpful to those who disagree with why JSON.minify() could be useful.

Kyle Simpson

Posted 2008-10-28T20:39:03.333

Reputation: 11 387

2Comments do not make sense in JSON. JSON is not meant to be a file format, just a data-packet interchange format. If you need something like commented JSON, use YAML instead. – Marnen Laibow-Koser – 2011-12-15T15:34:08.340

@Viktor Why would you need comments in a data packet? That wastes space. If for didactic purposes, just put them elsewhere, or accept that you're breaking the format. In an actual application, they shouldn't be necessary. – Marnen Laibow-Koser – 2012-03-07T00:07:50.177


You might find it interesting to hear, from the author of JSON, why comments were left out of the spec:

– MiniGod – 2013-01-31T03:29:22.747


@MiniGod I have already heard Doug's thoughts on this topic many times. I addressed them long ago in my blog post:

– Kyle Simpson – 2013-02-26T23:21:25.390

13@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 – 2014-03-28T22:09:27.100

1@StaxMan No. Comments in a data stream are just wasted bytes. If metadata like creation time can't be inferred from the stream itself, then why not make it actual, parseable content in the stream? Arguments for comments are shallow: if something is worth including, then it's worth including it as data. – Marnen Laibow-Koser – 2014-04-01T16:38:37.707

@StaxMan I believe I'm backing up everything I say with facts, so as not to make it just my personal opinion. If there's anything I haven't backed up sufficiently, let me know. "Your claim that all metadata ought to be data is just nonsense" No, you're demonstrably wrong here. The only reason to include metadata, I think, is so it can be parsed. If it's going to be parsed, then just make it real data, not comments. Do you have a use case in mind for which this won't work? – Marnen Laibow-Koser – 2014-04-09T03:14:31.437

@StaxMan "most other text formats recognize this much (XML and YAML have comments)" XML and YAML are designed for files; JSON was simply extracted from JavaScript, and I think it makes a horrible file syntax (YAML and even XML work better in this case). It's true that JSON files may occasionally need comments, but JSON files are themselves a bad idea when YAML does the same job better. :) – Marnen Laibow-Koser – 2014-04-09T03:16:53.670

2My canonical use case are log files that are streamed over to be aggregated or stored; so stream/file distinction is virtual and transient. As to skipping: all properties are visible, and there are two main ways to deal with it -- (a) classical, you must know what everything is (to the degree at least that you can skip it), or (b) "anything goes", i.e. just use what you know. It is only trivial to skip metadata in latter case. But I see that you can not conceive of the simple notion of diagnostics-only comments -- no point in arguing past each other here. – StaxMan – 2014-04-09T19:41:57.550

@StaxMan "My canonical use case are log files"—problematic in itself; JSON is not a good format for logging (too much punctuation compared to YAML or XML). "It is only trivial to skip metadata in latter case."—That's a strong argument for not using the "classical" method (in general, it's too easy to break it). "But I see that you can not conceive of the simple notion of diagnostics-only comments"—What do you mean by diagnostics-only comments? I can't conceive of it if you don't explain it. :) – Marnen Laibow-Koser – 2014-05-15T05:50:56.653

3JSON 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": "", "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=""><field type="TextField" name="name">foo</field><field type="IntegerField" name="customer_number">12345</field></object></django-objects> – ManicDee – 2014-06-16T05:28:52.267

@ManicDee You're right about the punctuation in XML; I was trying to be brief and wound up being inaccurate in that respect. Revised statement: JSON has too much punctuation compared to YAML, and is a poor file-oriented syntax compared to either YAML or XML. (For the record, I'd pick JSON for streams, YAML for files, and XML for nothing every time, unless there's a specific external need for XML.) – Marnen Laibow-Koser – 2014-07-09T15:38:42.390

2The problem with this answer is that JSON is a serialization format, and so a minifier has to be written for every language (or a built-in minifier for every parser). How am I supposed to find a json minifier for c now? – Blake – 2014-09-10T16:45:37.443

12If 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 – 2016-01-27T19:31:22.303

@KyleSimpson 404 on your blog link, update the link if you a new copy – Srinath Ganesh – 2016-05-24T11:42:45.757

The blog post link ("comments make sense in JSON") is broken: Server not found. Can you update your answer (e.g. remove the link, etc. if there isn't a new location for the blog post)? – Peter Mortensen – 2017-01-19T17:33:37.807

blog post link fixed. – Kyle Simpson – 2017-01-20T13:40:26.240

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. – Marc Lehmann – 2017-05-01T16:22:15.040

2Interesting the removal of commenting ability from JSON. Everywhere and always I am reminded to comment my code. Now I have a huge config/data file in JSON that cannot be commented for future reference because for some reason someone thought commenting unnecessary/silly. – JayJay123 – 2017-05-30T17:56:03.410


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: . On some large test files your implementation takes 74 seconds and mine 0.06 seconds.

– WizKid – 2011-08-25T09:16:57.470


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:

– Kyle Simpson – 2011-08-30T17:20:41.860

To throw my own two cents in, if JSON is supposed to be a pure "data-packet exchange format", then it should've been implemented as a strictly-binary format. As it stands, the data is represented as a human-readable string-based syntax, and it logically follows that anything designed to be readable by humans should also allow for comments. – Abion47 – 2018-11-12T20:20:10.307

3Perl's JSON supports # comments. – Johannes Ernst – 2011-11-14T17:36:11.250


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+

Artur Czajka

Posted 2008-10-28T20:39:03.333

Reputation: 10 717

151I thought JSON was to supposed to be more human readable than, say, XML? Comments are for readability. – intrepidis – 2012-10-14T13:00:36.417

18Anyway, 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 – 2012-10-14T13:04:37.270

2Removing /* */ comments also made JSON a better subset of YAML. – Schwern – 2012-11-29T07:47:17.940

1@Schwern But YAML does allow # comments, so your point is kind of muoot – Juan Mendes – 2013-04-04T17:50:12.707

1@JuanMendes I don't understand why that makes my point about JSON/YAML compatibility moot. What do you think my point was? – Schwern – 2013-04-04T18:28:59.487

@Schwern I took your point to be it shouldn't have comments because it makes it not a subset of YAML. I'm saying that YAML does have comments, so it seems wrong to use that as a reason why you wouldn't have comments in JSON. – Juan Mendes – 2013-04-04T23:22:22.770

4@JuanMendes Not so much "shouldn't" as it simply is a benefit of the change (personally I find it a pain that I can't comment in JSON files). Keep in mind that JSON is also a subset of Javascript, and YAML and Javascript have mutually incompatible comment syntax. YAML uses # but Javascript uses // and /* */. JSON can't use # as a comment without becoming incompatible with Javascript. JSON can't be a subset of both YAML and Javascript and have comments. – Schwern – 2013-04-05T02:26:06.770

9As liz lemon would say… "deal breaker, ladies"! jesus… so to test something with a line "omitted", aka "commented" (in the normal universe).. you have to DELETE the line? no thanks! gimme some good ole' rackety-brackety XML, any day! – Alex Gray – 2013-05-16T22:16:42.653

@ChrisNash It was not meant to be more readable than XML, just easily readable by humans. And, JSON is easily readable by humans. Comments add additional information, but don't make it any more or less easy to read for humans.

– Oscar Godson – 2013-08-02T18:18:24.253

58Personal 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 – 2013-09-23T02:28:34.580

1@caiosm1005 Writing own parser for well-defined format is always less-than-perfect. I found that formats like Java properties or plain old INI are far more suitable for configuration files. Java, C++, Python and nodejs all have built-in or library support for one or the other. I especially favor the INI files. It's either that or always supplement configs with a robust readme file. – Artur Czajka – 2013-09-24T12:22:12.713

17@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 – 2013-10-04T02:42:27.373

9Classic. I don't buy the argument that you must limit usability because someone might misuse a feature. That's simply dogmatic and short-sighted. The right thing to do is create a mechanism for including comments in JSON, just like every other language. We shouldn't be wasting bandwidth on a pointless philosophical jihad about maintaining "purity". Get over it, add comments, move on. – rakehell – 2014-05-29T17:52:44.150

12"I removed comments from JSON because I saw people were using them to hold parsing directive". By that logic, he should also have removed the string type. Terrible decision. – adelphus – 2014-06-12T14:22:53.527

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 – 2014-08-07T19:24:14.440

11Who flippin' cares if someone was using comments in their JSON to include parsing directives? Honestly. Ridiculous. So, if you put non-standard parsing directives for your own parser in a comment, a parser that follows the official spec will ignore them. Otherwise, people will either not use JSON, or resort to hacks to include comments as data, which is surely no better than having custom parsing directives in the comments. For that matter, people will also put their custom parsing directives into the JSON stream as data. It's a silly argument, and the inability to use comments is obnoxious. – Craig – 2014-09-15T06:48:53.967

Honestly; has nobody ever used comments in XML for their own custom processing directives? Did it destroy XML interoperability? Has there ever been another language or data format that allow for comments in the file? – Craig – 2014-09-15T06:54:53.580

4Not having comments in JSON feels wrong. Formatting (spaces, linefeeds) are allowed in JSON and there is no fundamental difference between formatting and comments. – Johannes Overmann – 2015-01-29T09:55:56.530

48That'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 – 2015-05-14T17:24:29.153

@PhilGoetz But that specific model has training wheels. The analogy would work better with a tricycle. If you don't like it, use another like YAML or a properties file. Not everything should be designed to grasp every possible features you can think about. – Winter – 2017-08-11T12:37:13.477

The whole point of JSON is that it contains only data. If you feel the need for comments, you should be using XML, not JSON. Same goes for processing instructions (XML has them too). Really, really...if you're using JSON for anything other than rectangular data (rows and cols), then you're probably wrong and should be using XML. – Peter Flynn – 2017-08-31T13:27:12.797

1Removing comments is a 'BAD IDEA'. As the comment is also data for the person reading it,removing them because they are not data is a bad argument. In addition, it can be argued that all comments in any language, specification file, config file, etc are data. Just because it is not intended for the machine it does not mean it's not data. – Mac – 2018-08-24T15:41:37.157



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

  "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": "",
    "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!


Posted 2008-10-28T20:39:03.333

Reputation: 4 749


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

– Quentin – 2013-08-02T13:50:02.437

1Right, 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. – Ped – 2013-08-02T13:57:49.420

96"all the implementations handle it the same" — That's a difficult thing to prove. – Quentin – 2013-08-02T14:20:40.950

86The order of elements in JSON is not guaranteed. That means the "last" item could change! – sep332 – 2013-08-02T14:33:10.613

2@sep332 they are in the case of a hand edited json/config file. – Tracker1 – 2013-08-02T14:36:32.360

8@Quentin from the rfc2119: "3. SHOULD This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course." – erdeszt – 2013-08-02T14:37:37.100

6@Tracker1 — The order is not guaranteed, because what matters is the parser not the person writing the file. The JSON specification doesn't describe what should happen if there are duplicate keys (it says that you SHOULD make them unique), so some parsers might take the first while others might take the last while others fall over. – Quentin – 2013-08-02T14:39:07.997


This clearly violates the spec (see above comments), don't do this.

– voidlogic – 2013-08-02T14:39:29.240

2@erdeszt — Yes, the full implications must be understood. There is no way to understand those without testing every JSON parser (and since people will keep writing new ones …). – Quentin – 2013-08-02T14:39:49.750

6It would be totally reasonable for a parser to discard values of existing keys instead of overwriting them. – Gipsy King – 2013-08-02T14:44:20.163

5There are over a hundred different implementations currently listed at I bet at least one of them doesn't handle it the same. – nemetroid – 2013-08-02T14:44:40.317

8I once had quite some trouble with JSON files that had double keys just because it was not explicitely disallowed in the spec. Please don't advise others to do this. – opyh – 2013-08-02T14:47:07.940

4My own implementation (for an embedded system, couldn't find an existing one that matched the requirements) always takes the first key in case of duplicates. You really can't assume this will work. – pdw – 2013-08-02T14:53:19.813

299NO - 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 – 2013-08-02T14:55:22.523

2@Quentin I'm just saying that the spec isn't clear about how to handle this case and this is a clever hack which is "legal" but of course discouraged. – erdeszt – 2013-08-02T14:58:39.587

16Downvoted. This is a bad idea, pure and simple. You're abusing a gray area of the JSON specification and it is irresponsible to be promoting such a practice to others. It's a hack; don't do it. – Brad Choate – 2013-08-02T16:04:41.073

10You're begging for this to blow up in your face. Like others mentioned, a parser may outright reject your JSON, echo back the "comment" instead of the value, or fail in mysterious ways, like pushing two events for the same key (streaming parsers, most likely). For example, the recent APK signature vulnerability was essentially exploiting the same thing, undefined behavior for multiple non-unique keys (file names), just in zip instead of JSON. – nmaier – 2013-08-02T16:19:59.580


That is wrong on so many levels I don't even know where to begin. I'll just put that here - - and try to forget what I just saw.

– Geoffrey Bachelet – 2013-08-02T18:13:45.690


See this question for error case:

– Paul Tyng – 2013-08-02T18:33:34.293

3Bad idea - leads to confusion, against spec, not future proof and JSLint disqualifies the JSON. – Praveen Vijayan – 2013-08-03T05:37:34.987

1This is a great hack in todays context. JSON parsing is streamlined both on the server side and browser side. All browsers after and including IE8 support JSON.parse. So really everybody should be using the built in JSON parse. You will use a custom parser for legacy reasons only. And it is highly unlikely the built in JSON parser will change its behaviour and break backward compatibility. – Santosh – 2013-08-03T06:13:00.360

... continued from above comment by me. The only thing we need to do now is to standardise it so that it is not confusing to the user. For example we could indicate that it is a comment by doing something like " this is a comment " – Santosh – 2013-08-03T06:21:16.410


As we've been working on RFC 4627bis at the IETF in the JSON working group (join us and help!, we have found four different approaches that implementors have used for duplicate names in an object: use the first; use the last; report all of them and let the caller pick one; return an error and stop parsing. If your data can't survive all of those approaches, it won't interoperate in practice.

– Joe Hildebrand – 2013-08-03T22:03:30.620


Bad hack. It's JSON parser matter. At least IAM policy file (AWS) doesn't accept duplicate JSON key.

– kyanny – 2013-08-04T03:06:42.503

9This is one of the worst answers I've ever seen on stackoverflow. It can break at any time and it is not so smart as it doesn't make it especially readable like regular comments. One may always wonder if we have an item that is a comment or a real piece of data. JSMin seems like a much cleaner (and more readable) solution. That said, the IT industry should still thank you for the joke. – Jeremyfa – 2013-08-04T17:28:56.107

Solr uses multiple Keys. This is incompatible with the major opensource search server!!! – fulmicoton – 2013-08-04T22:57:48.737


combine that with Eli's answer, and insert duplicate "_comment" keys all around, then you get the best of both worlds.

– depoulo – 2013-08-05T07:47:07.980

If you have a parser that errors when a duplicate key is found to prevent data loss by mistake, this would break... It is not a good idea to create comments this way, as they aren't comments and if the parser was using some logic so it wouldn't read top to bottom it would break too. Please don't use this as it is against the spec. – Jose Sutilo – 2013-08-05T11:43:27.007

8This answer is cancer. My dev. guys did the same without reading through the comments. Now we are burning ourselves while stream through the content from RPC server. – asyncwait – 2013-11-01T10:13:49.967


"all the implementations handle it the same" - jju has an option to throw on these jsons

– alex – 2014-01-04T00:26:23.323


This is the most controversial post on SO.

– bjb568 – 2014-04-11T18:45:38.680

1You could easily state that your "comment" properties either have a single string as their value, or an array of strings. That way you can include as many comment lines as you like, while staying valid JSON. – gnasher729 – 2014-10-16T11:48:38.347

1I really like the way you think.. Although the specifications state that the key names be unique, it is just a way of saying otherwise the last one overrides every other key – Akshay Khandelwal – 2015-09-16T03:45:15.487

@AkshayKhandelwal: You apparently failed to comprehend this comment. In a nutshell: There are four different strategies parsers choose when confronted with non-unique names in an object. Besides, the specification makes no guarantees with respect to persisting any ordering, so "last" doesn't make sense anyway. Stop spreading wishful thinking as if it were factually correct.

– IInspectable – 2017-04-17T16:49:40.140

1You are stepping into the region of implementation dependency. – Derek 朕會功夫 – 2017-08-17T20:47:31.610

1Have my upvote for the brazen courage to do this kind of thing. – Renan – 2017-08-31T19:22:47.720

This is a nice hack but unholy kind of hack. – Veerakran Sereerungruangkul – 2018-10-23T04:54:34.583

The jsondecode parser of matlab will create api_host and api_host_1 fields, etc .. – user3240484 – 2018-10-29T11:57:12.987


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 for JavaScript, Java, Python, PHP, Rust, Go, Ruby and C# libraries.


Posted 2008-10-28T20:39:03.333

Reputation: 25 052

if you look at the spec you'd see that it's a superset of json. you can convert from/to json. – laktak – 2014-06-12T14:53:11.817

12Upvoted. 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 – 2014-06-30T19:20:30.647


Sorry about that, @konsolebox. Perhaps you might reconsider your "well-defined JSON is your opinion" view after reading 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 – 2014-07-09T16:02:47.853


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: or stick with curmudgeony, yet unambiguous JSON.

– toolbear – 2014-08-07T18:25:56.387

2I 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 – 2015-02-10T15:15:18.443

11Whenever 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 – 2016-04-06T14:20:46.320


You can't. At least that's my experience from a quick glance at

JSON has its syntax visualized on that page. There isn't any note about comments.


Posted 2008-10-28T20:39:03.333

Reputation: 12 378


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

Marnen Laibow-Koser

Posted 2008-10-28T20:39:03.333

Reputation: 4 115

1Note that the converse is not true (valid YAML !=> valid JSON) – g33kz0r – 2012-09-11T04:01:35.690

11@g33kz0r Correct, hence my description of YAML as a near-superset of JSON. – Marnen Laibow-Koser – 2012-09-12T14:58:43.473

12@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 – 2014-03-28T12:57:24.527

3Downside: yaml library isn't shipped with Python. – Bleeding Fingers – 2014-04-15T10:06:03.260

5@BleedingFingers So install it... – Marnen Laibow-Koser – 2014-04-15T16:19:00.160


Agreed that this is a relevant alternative. Nevertheless, don't use YAML if you were already leaning towards JSON:

– toolbear – 2014-08-07T19:29:29.383

@toolbear: your linked comment suggests you don't know how to use YAML well. I've never had YAML bite me, ever. So yes, use YAML, even if you were already leaning towards JSON. – Marnen Laibow-Koser – 2014-08-13T19:25:09.600

4@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 – 2014-08-17T23:32:00.813

@toolbear Sounds like the fault of poorly written libraries; don't blame the format for that. And yeah, your claim of quoting ambiguities suggests lack of knowledge, though I'd be interested in looking at a particular case if you have one. However, the lack of knowledge might be on the part of the parser implementer, not necessarily you. – Marnen Laibow-Koser – 2014-08-18T20:38:11.390

2@marnen-laibow-koser, a format that accomplishes the same thing with a simpler spec is better. A pragmatic format with perfect implementations is better than an ideal format with imperfect implementations. Not all the blame for faulty libs lies on the implementors' shoulders; the YAML spec is long, dense, and obtuse. Its Wikipedia entry cites two examples of ambiguities; if one must put an emitter between a human and the format to protect them from ambiguities, the format loses its human friendly claim. JSON claims less and mostly succeeds where YAML claims more and falls short. – toolbear – 2014-08-25T11:45:36.407

3@marnen-laibow-koser, I've refuted your implication of my own incompetence, backed up my claims with specifics, and elaborated slightly on my preferences/biases that inform my YAML critique. Further comments by myself probably have diminishing returns. I'm confident of future readers' ability to make an informed choice. Aside from skirting close to an ad hominem attack, thank you for the discourse. The last word is yours should you desire it. – toolbear – 2014-08-25T11:56:29.793

1@toolbear No ad hominem attack was intended. "A pragmatic format with perfect implementations is better than an ideal format with imperfect implementations"—Not sure I agree. If the format is ideal (and implementable), then one can always make a good implementation. If the format isn't ideal, then even a perfect implementation won't be very good. :) "the YAML spec is long, dense, and obtuse"—That's not actually what "obtuse" means, but the YAML spec is quite clear. I don't see any ambiguities mentioned in Wikipedia; please cite specific sections of the article if I missed something. – Marnen Laibow-Koser – 2014-09-13T00:58:39.177

1yaml >> json . And python has a good yaml library. I have to roll my own in Scala - but still worth it. – javadba – 2016-10-02T05:35:45.667

This answer really should have been a comment. – bhspencer – 2018-05-02T18:30:54.087


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.


    "description":"A person",

You can provide documentation by using the description schema attribute.


Posted 2008-10-28T20:39:03.333

Reputation: 963

4Is JSON schema alive? It exists but is it supported by any known library? – Munhitsu – 2012-10-29T14:31:10.200


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 – 2012-11-27T11:34:05.587

4This only helps with structured documentation, not ad-hoc documentation – Juan Mendes – 2013-04-04T17:47:42.893

If you use clojure (and I'm sure you don't) there's a reasonably featured open-source JSON schema parser here:

– charleslparker – 2013-04-15T13:50:44.967

@Munhitsu Manatee.Json (.Net) extensively supports JSON schema. – gregsdennis – 2015-06-26T00:26:29.953

This isn't relevant for all situations. I have one where I have a manually configured JSON to be parsed by something else (a package manager) that has its own schema. In that I want a comment such as / It's better to use X instead from another package manager, however that manager doesn't provide X yet so. /. – jgmjgm – 2017-12-08T11:22:37.343


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.


Posted 2008-10-28T20:39:03.333

Reputation: 18 466

Opening that link timed out when I tried it: The connection to the server was reset while the page was loading. – Peter Mortensen – 2017-01-19T18:14:17.593


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" : [

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


Posted 2008-10-28T20:39:03.333

Reputation: 5 473

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 – 2015-11-06T21:47:04.573


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"


Posted 2008-10-28T20:39:03.333

Reputation: 3 744


Sorry, we can't use comments in JSON... See the syntax diagram for JSON on

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.


Posted 2008-10-28T20:39:03.333

Reputation: 1 660

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 – 2012-11-18T03:56:46.903

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 – 2014-08-07T19:22:52.340


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

– kenorb – 2016-09-02T12:17:17.120


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.

John T. Vonachen

Posted 2008-10-28T20:39:03.333

Reputation: 427

I agree and have written a JSON parser in Java, available at, that does exactly that. – Lawrence Dol – 2012-07-28T01:51:47.893

2Despite 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 – 2013-07-27T12:09:20.193

20"...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 – 2013-12-08T21:55:15.760

1What @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 – 2014-08-07T19:32:52.043

1Probably the best suggestion so far, though still an issue for keeping files as an interchange format, as they need pre-processing before use. – Orbling – 2011-02-25T11:04:33.360

One liner JS-compatible regex: myJson.replace(/("\/\/.*"|"\/\*(?:.|\n)*?")|(\/\/.*|\/\*(?:.|\n)*?\*\/)/g, "$1")

– Max Paperno – 2018-05-08T04:34:11.373


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


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


Posted 2008-10-28T20:39:03.333

Reputation: 3 585

It is hard to understand why someone would have problem with stating a fact. – dvdmn – 2014-07-29T14:17:30.890

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 – 2014-08-07T18:12:46.100

5I 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 – 2014-08-20T16:48:36.107


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.

Neil Albrock

Posted 2008-10-28T20:39:03.333

Reputation: 685

11It 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 – 2009-09-01T18:20:50.723

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 – 2013-06-25T14:50:28.763

1This 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 – 2014-08-07T19:35:06.290

3@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 – 2010-12-11T09:03:56.480

3Metadata 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 – 2011-09-06T04:55:58.053


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.


Posted 2008-10-28T20:39:03.333

Reputation: 2 309

1how many languages do you think supports YAML out of the box compared to json ? – momo – 2012-01-13T13:26:38.243

@Hamidam Over a dozen languages support yaml: - 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 – 2012-03-21T15:53:56.053


YAML interop is a lie: . If your instinct is to use JSON for configuration files, follow it.

– toolbear – 2014-08-07T19:10:08.170

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 – 2015-12-02T18:24:38.157

3For 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 – 2011-10-19T21:35:37.107


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

See another Stack Overflow question.


Posted 2008-10-28T20:39:03.333

Reputation: 4 170

And I believe that is why I see a comment in a screenshot on this ASP.NET vNext preview page (under package.json): although I haven't found anything in the spec yet.

– webXL – 2014-09-17T21:54:01.523


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.


Posted 2008-10-28T20:39:03.333

Reputation: 7 515

3Crockford 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 – 2014-08-07T19:14:21.703


JSON makes a lot of sense for config files and other local usage because it's ubiquitous and because it's much simpler than XML.

If people have strong reasons against having comments in JSON when communicating data (whether valid or not), then possibly JSON could be split into two:

  • JSON-COM: JSON on the wire, or rules that apply when communicating JSON data.
  • JSON-DOC: JSON document, or JSON in files or locally. Rules that define a valid JSON document.

JSON-DOC will allow comments, and other minor differences might exist such as handling whitespace. Parsers can easily convert from one spec to the other.

With regards to the remark made by Douglas Crockford on this issues (referenced by @Artur Czajka)

Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.

We're talking about a generic config file issue (cross language/platform), and he's answering with a JS specific utility!

Sure a JSON specific minify can be implemented in any language, but standardize this so it becomes ubiquitous across parsers in all languages and platforms so people stop wasting their time lacking the feature because they have good use-cases for it, looking the issue up in online forums, and getting people telling them it's a bad idea or suggesting it's easy to implement stripping comments out of text files.

The other issue is interoperability. Suppose you have a library or API or any kind of subsystem which has some config or data files associated with it. And this subsystem is to be accessed from different languages. Then do you go about telling people: by the way don't forget to strip out the comments from the JSON files before passing them to the parser!

Basel Shishani

Posted 2008-10-28T20:39:03.333

Reputation: 3 456

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 – 2014-08-07T19:19:52.100


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.


Posted 2008-10-28T20:39:03.333

Reputation: 1 196

2No. 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 – 2014-08-07T19:31:33.010

1I 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 – 2014-08-07T23:37:25.520

It's bad voodoo to serve up commented, and thus invalid JSON, which dojo.xhrGet() implicitly encourages by accepting. – toolbear – 2014-08-08T20:21:31.057

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 – 2014-09-15T07:03:06.013


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.

Smit Johnth

Posted 2008-10-28T20:39:03.333

Reputation: 630


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

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.


Posted 2008-10-28T20:39:03.333

Reputation: 4 361


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.

Manish Shrivastava

Posted 2008-10-28T20:39:03.333

Reputation: 17 818


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

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

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

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

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

First, canonicalize your JSON by minifying it:

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

Then encode your comment in binary:

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

Then steg your binary:

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

Here is your output:

$jsonWithComment = $steg . $jsonMin;

William Entriken

Posted 2008-10-28T20:39:03.333

Reputation: 18 966

1The 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 – 2014-09-24T18:15:00.120

For greater comment density, couldn't you encode your comment in ternary and use space, tab, and newline to steg it? – Claire Nielsen – 2018-09-26T19:44:28.947


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"}';
//=> {unicorn: 'cake'}


Posted 2008-10-28T20:39:03.333

Reputation: 6 807


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


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

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

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

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



Posted 2008-10-28T20:39:03.333

Reputation: 794

14You've emulated an INI file structure in JSON. Please, put down your Golden Hammer. – Artur Czajka – 2013-11-18T16:53:10.923


RFC says "The names within an object SHOULD be unique". Also see this person that is having an error parsing JSON like the above:

– William Entriken – 2014-06-10T15:58:29.520

If you're using a schema to validate the JSON, it may fail due to the extra fields. – gregsdennis – 2015-06-26T00:32:11.713

1If 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 – 2015-09-04T22:51:17.183


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


Posted 2008-10-28T20:39:03.333

Reputation: 471

8This 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. – None – 2014-02-12T20:24:25.017


RFC says: "The names within an object SHOULD be unique". See this error reported at:

– William Entriken – 2014-06-10T15:59:14.633

5Doing this is an invitation for creating JSON that blows up on you at some random point in the future. – toolbear – 2014-08-07T19:00:07.060

5There 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 – 2015-05-26T22:26:08.253

2Behaviour 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 – 2017-10-06T18:24:09.507

This is terribly bad advice. As others have pointed out before, the behavior is undefined. Different parsers will show different behavior. Some will return the first "param", some will return the second "param", some will stop with an error. It was said before, but this advice is so bad that it's worth repeating that it's bad. – Christian Hujer – 2018-01-01T07:12:03.093

This might work in a specific implementation but it would be brittle, unless you have control over whatever ingests the json and nothing else is going to use the json data. – ggb667 – 2018-01-16T16:44:14.703

@toolbear JSON does not "blow up". The parser does. It is a doubtful solution. But not worse than adding "_comment". Maybe better than nothing. – Rolf – 2018-02-14T02:30:14.120

It will not work on IE in strict mode! – Yogesh Jagdale – 2018-04-25T11:23:54.273

json is not ordered, so this will blow up approximately 50% of the time (at least in Go where if the ordering is not defined, it is randomized) – Darshan Chaudhary – 2018-05-16T10:35:10.737


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

Joshua Richardson

Posted 2008-10-28T20:39:03.333

Reputation: 920

7This 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 – 2013-12-08T21:58:52.763

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 – 2013-12-11T23:52:24.530

+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 – 2014-06-26T08:45:04.190

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 – 2014-06-27T03:13:55.250

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 – 2014-08-07T19:06:53.503

@AlexisWilke, "comments are definitively useless and pump lots of bandwidth for nothing" -- this is specifically why comments should be supported in the spec. Just look at the number of suggested workarounds that involve numerous different-but-similar ways of schlepping comments into the JSON as data, guaranteeing that a minification tool cannot remove the comments, guaranteeing that they get transmitted over the wire, and forcing the remote parser to deal with them with varying degrees of success. You try to force people ideologically, and they find ways around you. Just the way it is... – Craig – 2014-09-15T07:11:23.267

@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 # &lt;line#&gt; ... entries.) That makes it easy enough, I think. – Alexis Wilke – 2014-09-15T21:48:36.863

@AlexisWilke that's fine, except it isn't a JSON standard and you can't just presume I'm working on Linux and able to shell out and pipe my files through cpp--I'm not. So I added code to my program to strip out C/C++ comments. My point, really, is that people will find a way to add comments anyway, but they'll now add them as JSON data in a million slightly different formats that no automated tool can detect and remove from the data stream, so the attempt to remove comments will perversely guarantee the existence of comments in the JSON and bulking up data transfers. – Craig – 2014-09-16T14:39:13.760

@Craig, As a side note, cpp is available under MS-Windows. Although frankly writing your own little tool is probably as easy than messing around with cygwin or MinGW... Now I agree that it is not exactly JSON, but it looks like many interpreters do understand similar extension (C/C++ comments.) – Alexis Wilke – 2014-09-16T21:25:53.557

@AlexisWilke at some point, though, doesn't all that seem a little bit like going to heroic lengths just to be able to put a comment in your JSON file? In my case, I just need a bit of code (not an entire C/C++ compiler, running wrapped in an extra runtime library, no less if running under Cygwin/Ming), to strip comments out before I can pass my configuration files through the JSON parser. I also detect when the config files change and dynamically reload them, etc. How lame is it that I can't simply put comments in the files and not worry about it? It's super lame. That's how much. ;-) – Craig – 2014-09-16T23:45:00.970

Your JS interpreter solution is the Nancy Pelosi approach to JSON parsing: you have to pass it to find out what is in it. Of course there may be unintended side effects. – William Entriken – 2015-08-20T14:54:27.947

Note that the regexp doesn't work with URLs: "url": "http:// ... (oops!). You definitely need a real "JSON+comments" parser to strip comments. – Florian F – 2016-07-03T11:13:41.290

Yeah, no Douglas Crockford does not want people to include comments in JSON, that is why he removed annotations. See my answer. His position is 'do it with some non-interoperable pre-compiler, not in JSON' (eg. Jackson, etc). – Dominic Cerisano – 2018-11-05T02:55:35.010


Sigh. Why not just add fields, e.g.

    "note1" : "This demonstrates the provision of annotations within a JSON file",
    "field1" : 12,
    "field2" : "some text",

    "note2" : "Add more annotations as necessary"

Just make sure your "notex" names don't conflict with any real fields.

Steve Thomas

Posted 2008-10-28T20:39:03.333

Reputation: 156

5Just make sure your "notex" names don't conflict with any real fields. is the problem. This is not an arbitrary solution. – William Entriken – 2014-05-14T14:42:45.047

3This also presents the issue that the comments cannot be stripped out by a minification utility before transmission, unavoidably leading to bigger hunks of data being transmitted that serve no purpose on the other end of the transmission. I really feel like taking comment support out of the JSON spec is unfortunate. Specifically because people ARE going to hack solutions together. Taking the support out of the spec is an attempt at behavioral control that is simply going to fail and produce even bigger incompatibilities down the road due to proliferation of mutually-incompatible workarounds. – Craig – 2014-09-15T07:07:52.363

1in config files, I use {"/* ---- my section ----*/":0}. This is valid JSON, as JSON accepts any character in the key string. It will not collide with other properties and nobody cares or reordering. Still, 2 comments must not be the same. – olivr – 2015-04-08T03:46:52.763

1If you're using a schema to validate the JSON, it may fail due to the extra fields. – gregsdennis – 2015-06-26T00:30:20.753

Some object unmarshallers (e.g. Jackson, under some configurations) throw exceptions on unknown fields. – slim – 2016-10-20T09:28:01.290


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) {
    } else {
        var text = decomment(data); // removing comments
        var json = JSON.parse(text); // parsing JSON


{ value: 123 }

See also: gulp-decomment, grunt-decomment


Posted 2008-10-28T20:39:03.333

Reputation: 10 415


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

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

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

Dominic Cerisano

Posted 2008-10-28T20:39:03.333

Reputation: 1 401


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

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

    // Rainbows
    "unicorn": /* ❤ */ "cake"

Даниил Пронин

Posted 2008-10-28T20:39:03.333

Reputation: 734

Might as well minify that JSON while you're at it. See @kyle-simpson's answer about JSON.minify. – toolbear – 2014-08-07T18:54:29.430


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.


Posted 2008-10-28T20:39:03.333

Reputation: 4 428

I really thought there was no point going on to the second page of answers for this question but this is EXACTLY what I was looking for and works flawlessly! thanks. – rob – 2017-06-01T14:04:38.873


In my case, I need use comments for debug purposes, prior the output of the JSON structure. So I decided to use 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


Posted 2008-10-28T20:39:03.333

Reputation: 856


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's a 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."


Posted 2008-10-28T20:39:03.333

Reputation: 668


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) {
  $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.

Alexander Shostak

Posted 2008-10-28T20:39:03.333

Reputation: 174


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.


Posted 2008-10-28T20:39:03.333

Reputation: 8 375


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!


Posted 2008-10-28T20:39:03.333

Reputation: 782


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.


Posted 2008-10-28T20:39:03.333

Reputation: 6 008


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

    "": "this is a comment"


Posted 2008-10-28T20:39:03.333

Reputation: 2 669


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


Posted 2008-10-28T20:39:03.333

Reputation: 626


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

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


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


valid_json_str = json_str.replace(/\/\/[^\n]*/gim.'').replace(/\/\*.*?\*\//gim,'')


Posted 2008-10-28T20:39:03.333

Reputation: 2 420


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


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

Maurício Giordano

Posted 2008-10-28T20:39:03.333

Reputation: 1 043

4Your regexp would remove things like /*hey*/ even from inside strings. – 6502 – 2014-08-03T06:09:04.493

Good catch! So just change some stuff on regex. – Maurício Giordano – 2014-08-05T18:10:24.670

1Regular expressions for structured languages are notoriously hard to get right. Check out @kyle-simpson's answer about JSON.minify as an alternative to ad hoc regexps. – toolbear – 2014-08-07T18:57:20.787

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. – meagar – 2018-09-05T13:07:47.357