[json] Can comments be used in JSON?

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

This question is related to json comments

The answer is


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

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

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

var strip_json_comments = require('strip-json-comments')
var json = '{/*rainbows*/"unicorn":"cake"}';
JSON.parse(strip_json_comments(json));
//=> {unicorn: 'cake'}

If you are using the Newtonsoft.Json library with ASP.NET to read/deserialize you can use comments in the JSON content:

//"name": "string"

//"id": int

or

/* This is a

comment example */

PS: Single-line comments are only supported with 6+ versions of Newtonsoft Json.

Additional note for people who can't think out of the box: I use the JSON format for basic settings in an ASP.NET web application I made. I read the file, convert it into the settings object with the Newtonsoft library and use it when necessary.

I prefer writing comments about each individual setting in the JSON file itself, and I really don't care about the integrity of the JSON format as long as the library I use is OK with it.

I think this is an 'easier to use/understand' way than creating a separate 'settings.README' file and explaining the settings in it.

If you have a problem with this kind of usage; sorry, the genie is out of the lamp. People would find other usages for JSON format, and there is nothing you can do about it.


Disclaimer: This is silly

There is actually a way to add comments, and stay within the specification (no additional parser needed). It will not result into human-readable comments without any sort of parsing though.

You could abuse the following:

Insignificant whitespace is allowed before or after any token. Whitespace is any sequence of one or more of the following code points: character tabulation (U+0009), line feed (U+000A), carriage return (U+000D), and space (U+0020).

In a hacky way, you can abuse this to add a comment. For instance: start and end your comment with a tab. Encode the comment in base3 and use the other whitespace characters to represent them. For instance.

010212 010202 011000 011000 011010 001012 010122 010121 011021 010202 001012 011022 010212 011020 010202 010202

(hello base three in ASCII) But instead of 0 use space, for 1 use line feed and for 2 use carriage return.

This will just leave you with a lot of unreadable whitespace (unless you make an IDE plugin to encode/decode it on the fly).

I never even tried this, for obvious reasons and neither should you.


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

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

You should write a JSON schema instead. JSON schema is currently a proposed Internet draft specification. Besides documentation, the schema can also be used for validating your JSON data.

Example:

{
    "description":"A person",
    "type":"object",
    "properties":
        {
            "name":
                {
                    "type":"string"
                },
            "age":
                {
                    "type":"integer",
                    "maximum":125
                }
        }
}

You can provide documentation by using the description schema attribute.


In my case, I need to use comments for debug purposes just before the output of the JSON. So I put the debug information in the HTTP header, to avoid breaking the client:

header("My-Json-Comment: Yes, I know it's a workaround ;-) ");

Enter image description here


Include comments if you choose; strip them out with a minifier before parsing or transmitting.

I just released JSON.minify() which strips out comments and whitespace from a block of JSON and makes it valid JSON that can be parsed. So, you might use it like:

JSON.parse(JSON.minify(my_str));

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

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

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


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.


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

See another Stack Overflow question.


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

  • https://www.json.org
  • RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON)
  • RFC 8259 The JavaScript Object Notation (JSON) Data Interchange Format (supercedes RFCs 4627, 7158, 7159)

There is a good solution (hack), which is valid JSON, but it will not work in all cases (see comments below). Just make the same key twice (or more). For example:

{
  "param" : "This is the comment place",
  "param" : "This is value place",
}

So JSON will understand this as:

{
  "param" : "This is value place",
}

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.


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

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

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

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

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


First, canonicalize your JSON by minifying it:

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

Then encode your comment in binary:

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

Then steg your binary:

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

Here is your output:

$jsonWithComment = $steg . $jsonMin;

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


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.


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.


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

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

You should write a JSON schema instead. JSON schema is currently a proposed Internet draft specification. Besides documentation, the schema can also be used for validating your JSON data.

Example:

{
    "description":"A person",
    "type":"object",
    "properties":
        {
            "name":
                {
                    "type":"string"
                },
            "age":
                {
                    "type":"integer",
                    "maximum":125
                }
        }
}

You can provide documentation by using the description schema attribute.


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.


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


The JSON specification does not support comments, // or /* */ style.

But some JSON parsing libraries and IDEs support them.

Like:

  1. JSON5
  2. Visual Studio Code
  3. Commentjson

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.


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

You can use simple preprocessing via regular expressions. For instance, the following function will decode commented JSON in PHP:

function json_decode_commented ($data, $objectsAsArrays = false, $maxDepth = 512, $opts = 0) {
  $data = preg_replace('~
    (" (?:[^"\\\\] | \\\\\\\\ | \\\\")*+ ") | \# [^\v]*+ | // [^\v]*+ | /\* .*? \*/
  ~xs', '$1', $data);

  return json_decode($data, $objectsAsArrays, $maxDepth, $opts);
}

It supports all PHP-style comments: /*, #, //. String literals are preserved as is.


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

  • https://www.json.org
  • RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON)
  • RFC 8259 The JavaScript Object Notation (JSON) Data Interchange Format (supercedes RFCs 4627, 7158, 7159)

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.


This entire thread assumes that adding comments is the only improvement that needs to be made to JSON. If someone doesn't want comments in JSON because it's to be used for serialization, just omit the comments. The same goes for whitespace. But why stop there? Why are quotation marks required in JSON? They add nothing useful.

The only reason I can think of for JSON to be so rigid is if parsing is difficult. But it isn't. Almost any programmer can write a JSON parser, in either direction.

I want JSON to be readable and efficient (brief), and useful for data transmission, configuration files, and lots more. Both of these requirements are satisfied by the following example:

{stringA: stringB, stringC: stringD, [stringE, stringF]}

Shorter than any existing JSON specification, but just as readable and more efficient.

Need to include quotation marks, apostrophes, commas, or brackets in a property or value? Just enclose them in question marks or apostrophes (with backslash escape), just like in JavaScript.

But please make quotation marks optional. Why? Because JSON cannot contain variable or function names (to avoid injection attacks), so quotation marks don't provide any disambiguation. We already know that all the data are strings. So, please, leave out the quotation marks already, unless they are really needed.


Not technically. But you can workaround as follows.

{
  "json": "actual data goes here, comments below",
  "comment1": "Lorem ipsum dolor sit amet",
  "comment2": "consectetur adipiscing elit"
}

Just put the comments in the data. If you number them to make each key path unique, you should have no problems.


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

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.


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!


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

See another Stack Overflow question.


Disclaimer: This is silly

There is actually a way to add comments, and stay within the specification (no additional parser needed). It will not result into human-readable comments without any sort of parsing though.

You could abuse the following:

Insignificant whitespace is allowed before or after any token. Whitespace is any sequence of one or more of the following code points: character tabulation (U+0009), line feed (U+000A), carriage return (U+000D), and space (U+0020).

In a hacky way, you can abuse this to add a comment. For instance: start and end your comment with a tab. Encode the comment in base3 and use the other whitespace characters to represent them. For instance.

010212 010202 011000 011000 011010 001012 010122 010121 011021 010202 001012 011022 010212 011020 010202 010202

(hello base three in ASCII) But instead of 0 use space, for 1 use line feed and for 2 use carriage return.

This will just leave you with a lot of unreadable whitespace (unless you make an IDE plugin to encode/decode it on the fly).

I never even tried this, for obvious reasons and neither should you.


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

Sure you can comment JSON. To read a commented JSON file from JavaScript you can strip comments before parsing it (see the code below). I'm sure this code can be improved, but it is easy to understand for those who use regular expressions.

I use commented JSON files to specify neuron shapes for my synthetic reflex systems. I also use commented JSON to store intermediate states for a running neuron system. It is very convenient to have comments. Don't listen to didacts who tell you they are a bad idea.

fetch(filename).then(function(response) {
    return response.text();
}).then(function(commented) {
    return commented.
        replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '$1').
        replace(/\r/,"\n").
        replace(/\n[\n]+/,"\n");
}).then(function(clean) {
    return JSON.parse(clean);
}).then(function(json) {
    // Do what you want with the JSON object.
});

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!


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

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

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

var strip_json_comments = require('strip-json-comments')
var json = '{/*rainbows*/"unicorn":"cake"}';
JSON.parse(strip_json_comments(json));
//=> {unicorn: 'cake'}

Yes, the new standard, JSON5 allows the C++ style comments, among many other extensions:

// A single line comment.

/* A multi-
   line comment. */

The JSON5 Data Interchange Format (JSON5) is a superset of JSON that aims to alleviate some of the limitations of JSON. It is fully backwards compatible, and using it is probably better than writing the custom non standard parser, turning non standard features on for the existing one or using various hacks like string fields for commenting. Or, if the parser in use supports, simply agree we are using JSON 5 subset that is JSON and C++ style comments. It is much better than we tweak JSON standard the way we see fit.

There is already npm package, Python package, Java package and C library available. It is backwards compatible. I see no reason to stay with the "official" JSON restrictions.

I think that removing comments from JSON has been driven by the same reasons as removing the operator overloading in Java: can be used the wrong way yet some clearly legitimate use cases were overlooked. For operator overloading, it is matrix algebra and complex numbers. For JSON comments, its is configuration files and other documents that may be written, edited or read by humans and not just by parser.


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

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.


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

From the creator of JSON:

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

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

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

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

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

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

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

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

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


Yes. You can put comments in a JSON file.

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

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

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

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

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


Comments are not an official standard, although some parsers support C++-style comments. One that I use is JsonCpp. In the examples there is this one:

// Configuration options
{
    // Default encoding for text
    "encoding" : "UTF-8",

    // Plug-ins loaded at start-up
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],

    // Tab indent size
    "indent" : { "length" : 3, "use_space": true }
}

jsonlint does not validate this. So comments are a parser specific extension and not standard.

Another parser is JSON5.

An alternative to JSON TOML.

A further alternative is jsonc.

The latest version of nlohmann/json has optional support for ignoring comments on parsing.


Include comments if you choose; strip them out with a minifier before parsing or transmitting.

I just released JSON.minify() which strips out comments and whitespace from a block of JSON and makes it valid JSON that can be parsed. So, you might use it like:

JSON.parse(JSON.minify(my_str));

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

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

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


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;

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

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

###PHP

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

###JavaScript

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

Yes, you can, but your parse will probably fail (there is no standard).

To parse it you should remove those comments, or by hand, or using a regular expression:

It replaces any comments, like:

/****
 * Hey
 */

/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/

It replaces any comments, like:

// Hey

/\/\/.*/

In JavaScript, you could do something like this:

jsonString = jsonString.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/, "").replace(/\/\/.*/,"")
var object = JSON.parse(jsonString);

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

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


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.


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

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!


You can use JSON with comments in it, if you load it as a text file, and then remove comments.

For example, you can use decomment library for that. Below is a complete example.

Input JSON (file input.js):

/*
* multi-line comments
**/
{
    "value": 123 // one-line comment
}

Test Application:

var decomment = require('decomment');
var fs = require('fs');

fs.readFile('input.js', 'utf8', function (err, data) {
    if (err) {
        console.log(err);
    } else {
        var text = decomment(data); // removing comments
        var json = JSON.parse(text); // parsing JSON
        console.log(json);
    }
});

Output:

{ value: 123 }

See also: gulp-decomment, grunt-decomment


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

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.


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

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


You can use simple preprocessing via regular expressions. For instance, the following function will decode commented JSON in PHP:

function json_decode_commented ($data, $objectsAsArrays = false, $maxDepth = 512, $opts = 0) {
  $data = preg_replace('~
    (" (?:[^"\\\\] | \\\\\\\\ | \\\\")*+ ") | \# [^\v]*+ | // [^\v]*+ | /\* .*? \*/
  ~xs', '$1', $data);

  return json_decode($data, $objectsAsArrays, $maxDepth, $opts);
}

It supports all PHP-style comments: /*, #, //. String literals are preserved as is.


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.


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.


JSON doesn't allow comments, per se. The reasoning is utterly foolish, because you can use JSON itself to create comments, which obviates the reasoning entirely, and loads the parser data space for no good reason at all for exactly the same result and potential issues, such as they are: a JSON file with comments.

If you try to put comments in (using // or /* */ or # for instance), then some parsers will fail because this is strictly not within the JSON specification. So you should never do that.

Here, for instance, where my image manipulation system has saved image notations and some basic formatted (comment) information relating to them (at the bottom):

{
    "Notations": [
        {
            "anchorX": 333,
            "anchorY": 265,
            "areaMode": "Ellipse",
            "extentX": 356,
            "extentY": 294,
            "opacity": 0.5,
            "text": "Elliptical area on top",
            "textX": 333,
            "textY": 265,
            "title": "Notation 1"
        },
        {
            "anchorX": 87,
            "anchorY": 385,
            "areaMode": "Rectangle",
            "extentX": 109,
            "extentY": 412,
            "opacity": 0.5,
            "text": "Rect area\non bottom",
            "textX": 98,
            "textY": 385,
            "title": "Notation 2"
        },
        {
            "anchorX": 69,
            "anchorY": 104,
            "areaMode": "Polygon",
            "extentX": 102,
            "extentY": 136,
            "opacity": 0.5,
            "pointList": [
                {
                    "i": 0,
                    "x": 83,
                    "y": 104
                },
                {
                    "i": 1,
                    "x": 69,
                    "y": 136
                },
                {
                    "i": 2,
                    "x": 102,
                    "y": 132
                },
                {
                    "i": 3,
                    "x": 83,
                    "y": 104
                }
            ],
            "text": "Simple polygon",
            "textX": 85,
            "textY": 104,
            "title": "Notation 3"
        }
    ],
    "imageXW": 512,
    "imageYW": 512,
    "imageName": "lena_std.ato",
    "tinyDocs": {
        "c01": "JSON image notation data:",
        "c02": "-------------------------",
        "c03": "",
        "c04": "This data contains image notations and related area",
        "c05": "selection information that provides a means for an",
        "c06": "image gallery to display notations with elliptical,",
        "c07": "rectangular, polygonal or freehand area indications",
        "c08": "over an image displayed to a gallery visitor.",
        "c09": "",
        "c10": "X and Y positions are all in image space. The image",
        "c11": "resolution is given as imageXW and imageYW, which",
        "c12": "you use to scale the notation areas to their proper",
        "c13": "locations and sizes for your display of the image,",
        "c14": "regardless of scale.",
        "c15": "",
        "c16": "For Ellipses, anchor is the  center of the ellipse,",
        "c17": "and the extents are the X and Y radii respectively.",
        "c18": "",
        "c19": "For Rectangles, the anchor is the top left and the",
        "c20": "extents are the bottom right.",
        "c21": "",
        "c22": "For Freehand and Polygon area modes, the pointList",
        "c23": "contains a series of numbered XY points. If the area",
        "c24": "is closed, the last point will be the same as the",
        "c25": "first, so all you have to be concerned with is drawing",
        "c26": "lines between the points in the list. Anchor and extent",
        "c27": "are set to the top left and bottom right of the indicated",
        "c28": "region, and can be used as a simplistic rectangular",
        "c29": "detect for the mouse hover position over these types",
        "c30": "of areas.",
        "c31": "",
        "c32": "The textx and texty positions provide basic positioning",
        "c33": "information to help you locate the text information",
        "c34": "in a reasonable location associated with the area",
        "c35": "indication.",
        "c36": "",
        "c37": "Opacity is a value between 0 and 1, where .5 represents",
        "c38": "a 50% opaque backdrop and 1.0 represents a fully opaque",
        "c39": "backdrop. Recommendation is that regions be drawn",
        "c40": "only if the user hovers the pointer over the image,",
        "c41": "and that the text associated with the regions be drawn",
        "c42": "only if the user hovers the pointer over the indicated",
        "c43": "region."
    }
}

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.


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.


In my case, I need to use comments for debug purposes just before the output of the JSON. So I put the debug information in the HTTP header, to avoid breaking the client:

header("My-Json-Comment: Yes, I know it's a workaround ;-) ");

Enter image description here


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.


Comments are not an official standard, although some parsers support C++-style comments. One that I use is JsonCpp. In the examples there is this one:

// Configuration options
{
    // Default encoding for text
    "encoding" : "UTF-8",

    // Plug-ins loaded at start-up
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],

    // Tab indent size
    "indent" : { "length" : 3, "use_space": true }
}

jsonlint does not validate this. So comments are a parser specific extension and not standard.

Another parser is JSON5.

An alternative to JSON TOML.

A further alternative is jsonc.

The latest version of nlohmann/json has optional support for ignoring comments on parsing.


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

{
    "https://schema.org/comment": "this is a comment"
}

No, JSON cannot have comments directly. However, as suggested by this, you can achieve a similar effect by doing something like

{
    "//name": "Name comment here",
    "name": "Jack",

    "//age": "Age comment here",
    "age": "25"
}

Most JSON parsers will ignore properties that are not mapped.


You can have comments in JSONP, but not in pure JSON. I've just spent an hour trying to make my program work with this example from Highcharts: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?

If you follow the link, you will see

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

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

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


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

{

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

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

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

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

}

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

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


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.


You can use JSON with comments in it, if you load it as a text file, and then remove comments.

For example, you can use decomment library for that. Below is a complete example.

Input JSON (file input.js):

/*
* multi-line comments
**/
{
    "value": 123 // one-line comment
}

Test Application:

var decomment = require('decomment');
var fs = require('fs');

fs.readFile('input.js', 'utf8', function (err, data) {
    if (err) {
        console.log(err);
    } else {
        var text = decomment(data); // removing comments
        var json = JSON.parse(text); // parsing JSON
        console.log(json);
    }
});

Output:

{ value: 123 }

See also: gulp-decomment, grunt-decomment


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

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


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!


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

{
    "https://schema.org/comment": "this is a comment"
}

This entire thread assumes that adding comments is the only improvement that needs to be made to JSON. If someone doesn't want comments in JSON because it's to be used for serialization, just omit the comments. The same goes for whitespace. But why stop there? Why are quotation marks required in JSON? They add nothing useful.

The only reason I can think of for JSON to be so rigid is if parsing is difficult. But it isn't. Almost any programmer can write a JSON parser, in either direction.

I want JSON to be readable and efficient (brief), and useful for data transmission, configuration files, and lots more. Both of these requirements are satisfied by the following example:

{stringA: stringB, stringC: stringD, [stringE, stringF]}

Shorter than any existing JSON specification, but just as readable and more efficient.

Need to include quotation marks, apostrophes, commas, or brackets in a property or value? Just enclose them in question marks or apostrophes (with backslash escape), just like in JavaScript.

But please make quotation marks optional. Why? Because JSON cannot contain variable or function names (to avoid injection attacks), so quotation marks don't provide any disambiguation. We already know that all the data are strings. So, please, leave out the quotation marks already, unless they are really needed.


If you are using the Newtonsoft.Json library with ASP.NET to read/deserialize you can use comments in the JSON content:

//"name": "string"

//"id": int

or

/* This is a

comment example */

PS: Single-line comments are only supported with 6+ versions of Newtonsoft Json.

Additional note for people who can't think out of the box: I use the JSON format for basic settings in an ASP.NET web application I made. I read the file, convert it into the settings object with the Newtonsoft library and use it when necessary.

I prefer writing comments about each individual setting in the JSON file itself, and I really don't care about the integrity of the JSON format as long as the library I use is OK with it.

I think this is an 'easier to use/understand' way than creating a separate 'settings.README' file and explaining the settings in it.

If you have a problem with this kind of usage; sorry, the genie is out of the lamp. People would find other usages for JSON format, and there is nothing you can do about it.


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


Yes, the new standard, JSON5 allows the C++ style comments, among many other extensions:

// A single line comment.

/* A multi-
   line comment. */

The JSON5 Data Interchange Format (JSON5) is a superset of JSON that aims to alleviate some of the limitations of JSON. It is fully backwards compatible, and using it is probably better than writing the custom non standard parser, turning non standard features on for the existing one or using various hacks like string fields for commenting. Or, if the parser in use supports, simply agree we are using JSON 5 subset that is JSON and C++ style comments. It is much better than we tweak JSON standard the way we see fit.

There is already npm package, Python package, Java package and C library available. It is backwards compatible. I see no reason to stay with the "official" JSON restrictions.

I think that removing comments from JSON has been driven by the same reasons as removing the operator overloading in Java: can be used the wrong way yet some clearly legitimate use cases were overlooked. For operator overloading, it is matrix algebra and complex numbers. For JSON comments, its is configuration files and other documents that may be written, edited or read by humans and not just by parser.


Sure you can comment JSON. To read a commented JSON file from JavaScript you can strip comments before parsing it (see the code below). I'm sure this code can be improved, but it is easy to understand for those who use regular expressions.

I use commented JSON files to specify neuron shapes for my synthetic reflex systems. I also use commented JSON to store intermediate states for a running neuron system. It is very convenient to have comments. Don't listen to didacts who tell you they are a bad idea.

fetch(filename).then(function(response) {
    return response.text();
}).then(function(commented) {
    return commented.
        replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '$1').
        replace(/\r/,"\n").
        replace(/\n[\n]+/,"\n");
}).then(function(clean) {
    return JSON.parse(clean);
}).then(function(json) {
    // Do what you want with the JSON object.
});

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+


JSON does not support comments. It was also never intended to be used for configuration files where comments would be needed.

Hjson is a configuration file format for humans. Relaxed syntax, fewer mistakes, more comments.

Hjson intro

See hjson.github.io for JavaScript, Java, Python, PHP, Rust, Go, Ruby, C++ and C# libraries.


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.


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

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

{
    // Rainbows
    "unicorn": /* ? */ "cake"
}

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

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

{
    // Rainbows
    "unicorn": /* ? */ "cake"
}

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

From the creator of JSON:

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

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

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

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

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

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

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

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

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


Yes, you can, but your parse will probably fail (there is no standard).

To parse it you should remove those comments, or by hand, or using a regular expression:

It replaces any comments, like:

/****
 * Hey
 */

/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/

It replaces any comments, like:

// Hey

/\/\/.*/

In JavaScript, you could do something like this:

jsonString = jsonString.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/, "").replace(/\/\/.*/,"")
var object = JSON.parse(jsonString);

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.


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.


The JSON specification does not support comments, // or /* */ style.

But some JSON parsing libraries and IDEs support them.

Like:

  1. JSON5
  2. Visual Studio Code
  3. Commentjson

JSON doesn't allow comments, per se. The reasoning is utterly foolish, because you can use JSON itself to create comments, which obviates the reasoning entirely, and loads the parser data space for no good reason at all for exactly the same result and potential issues, such as they are: a JSON file with comments.

If you try to put comments in (using // or /* */ or # for instance), then some parsers will fail because this is strictly not within the JSON specification. So you should never do that.

Here, for instance, where my image manipulation system has saved image notations and some basic formatted (comment) information relating to them (at the bottom):

{
    "Notations": [
        {
            "anchorX": 333,
            "anchorY": 265,
            "areaMode": "Ellipse",
            "extentX": 356,
            "extentY": 294,
            "opacity": 0.5,
            "text": "Elliptical area on top",
            "textX": 333,
            "textY": 265,
            "title": "Notation 1"
        },
        {
            "anchorX": 87,
            "anchorY": 385,
            "areaMode": "Rectangle",
            "extentX": 109,
            "extentY": 412,
            "opacity": 0.5,
            "text": "Rect area\non bottom",
            "textX": 98,
            "textY": 385,
            "title": "Notation 2"
        },
        {
            "anchorX": 69,
            "anchorY": 104,
            "areaMode": "Polygon",
            "extentX": 102,
            "extentY": 136,
            "opacity": 0.5,
            "pointList": [
                {
                    "i": 0,
                    "x": 83,
                    "y": 104
                },
                {
                    "i": 1,
                    "x": 69,
                    "y": 136
                },
                {
                    "i": 2,
                    "x": 102,
                    "y": 132
                },
                {
                    "i": 3,
                    "x": 83,
                    "y": 104
                }
            ],
            "text": "Simple polygon",
            "textX": 85,
            "textY": 104,
            "title": "Notation 3"
        }
    ],
    "imageXW": 512,
    "imageYW": 512,
    "imageName": "lena_std.ato",
    "tinyDocs": {
        "c01": "JSON image notation data:",
        "c02": "-------------------------",
        "c03": "",
        "c04": "This data contains image notations and related area",
        "c05": "selection information that provides a means for an",
        "c06": "image gallery to display notations with elliptical,",
        "c07": "rectangular, polygonal or freehand area indications",
        "c08": "over an image displayed to a gallery visitor.",
        "c09": "",
        "c10": "X and Y positions are all in image space. The image",
        "c11": "resolution is given as imageXW and imageYW, which",
        "c12": "you use to scale the notation areas to their proper",
        "c13": "locations and sizes for your display of the image,",
        "c14": "regardless of scale.",
        "c15": "",
        "c16": "For Ellipses, anchor is the  center of the ellipse,",
        "c17": "and the extents are the X and Y radii respectively.",
        "c18": "",
        "c19": "For Rectangles, the anchor is the top left and the",
        "c20": "extents are the bottom right.",
        "c21": "",
        "c22": "For Freehand and Polygon area modes, the pointList",
        "c23": "contains a series of numbered XY points. If the area",
        "c24": "is closed, the last point will be the same as the",
        "c25": "first, so all you have to be concerned with is drawing",
        "c26": "lines between the points in the list. Anchor and extent",
        "c27": "are set to the top left and bottom right of the indicated",
        "c28": "region, and can be used as a simplistic rectangular",
        "c29": "detect for the mouse hover position over these types",
        "c30": "of areas.",
        "c31": "",
        "c32": "The textx and texty positions provide basic positioning",
        "c33": "information to help you locate the text information",
        "c34": "in a reasonable location associated with the area",
        "c35": "indication.",
        "c36": "",
        "c37": "Opacity is a value between 0 and 1, where .5 represents",
        "c38": "a 50% opaque backdrop and 1.0 represents a fully opaque",
        "c39": "backdrop. Recommendation is that regions be drawn",
        "c40": "only if the user hovers the pointer over the image,",
        "c41": "and that the text associated with the regions be drawn",
        "c42": "only if the user hovers the pointer over the indicated",
        "c43": "region."
    }
}

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.


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.


DISCLAIMER: YOUR WARRANTY IS VOID

As has been pointed out, this hack takes advantage of the implementation of the spec. Not all JSON parsers will understand this sort of JSON. Streaming parsers in particular will choke.

It's an interesting curiosity, but you should really not be using it for anything at all. Below is the original answer.


I've found a little hack that allows you to place comments in a JSON file that will not affect the parsing, or alter the data being represented in any way.

It appears that when declaring an object literal you can specify two values with the same key, and the last one takes precedence. Believe it or not, it turns out that JSON parsers work the same way. So we can use this to create comments in the source JSON that will not be present in a parsed object representation.

({a: 1, a: 2});
// => Object {a: 2}
Object.keys(JSON.parse('{"a": 1, "a": 2}')).length; 
// => 1

If we apply this technique, your commented JSON file might look like this:

{
  "api_host" : "The hostname of your API server. You may also specify the port.",
  "api_host" : "hodorhodor.com",

  "retry_interval" : "The interval in seconds between retrying failed API calls",
  "retry_interval" : 10,

  "auth_token" : "The authentication token. It is available in your developer dashboard under 'Settings'",
  "auth_token" : "5ad0eb93697215bc0d48a7b69aa6fb8b",

  "favorite_numbers": "An array containing my all-time favorite numbers",
  "favorite_numbers": [19, 13, 53]
}

The above code is valid JSON. If you parse it, you'll get an object like this:

{
    "api_host": "hodorhodor.com",
    "retry_interval": 10,
    "auth_token": "5ad0eb93697215bc0d48a7b69aa6fb8b",
    "favorite_numbers": [19,13,53]
}

Which means there is no trace of the comments, and they won't have weird side-effects.

Happy hacking!


Yes. You can put comments in a JSON file.

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

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

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

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

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


JSON does not support comments. It was also never intended to be used for configuration files where comments would be needed.

Hjson is a configuration file format for humans. Relaxed syntax, fewer mistakes, more comments.

Hjson intro

See hjson.github.io for JavaScript, Java, Python, PHP, Rust, Go, Ruby, C++ and C# libraries.


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

{

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

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

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

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

}

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

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

import json, re

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

print(parse_json("""
{
  // This is a comment
  "name": "value" // so is this
  // "name": "value"
  // the above line gets removed
}
"""))

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.


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.


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

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

###PHP

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

###JavaScript

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

DISCLAIMER: YOUR WARRANTY IS VOID

As has been pointed out, this hack takes advantage of the implementation of the spec. Not all JSON parsers will understand this sort of JSON. Streaming parsers in particular will choke.

It's an interesting curiosity, but you should really not be using it for anything at all. Below is the original answer.


I've found a little hack that allows you to place comments in a JSON file that will not affect the parsing, or alter the data being represented in any way.

It appears that when declaring an object literal you can specify two values with the same key, and the last one takes precedence. Believe it or not, it turns out that JSON parsers work the same way. So we can use this to create comments in the source JSON that will not be present in a parsed object representation.

({a: 1, a: 2});
// => Object {a: 2}
Object.keys(JSON.parse('{"a": 1, "a": 2}')).length; 
// => 1

If we apply this technique, your commented JSON file might look like this:

{
  "api_host" : "The hostname of your API server. You may also specify the port.",
  "api_host" : "hodorhodor.com",

  "retry_interval" : "The interval in seconds between retrying failed API calls",
  "retry_interval" : 10,

  "auth_token" : "The authentication token. It is available in your developer dashboard under 'Settings'",
  "auth_token" : "5ad0eb93697215bc0d48a7b69aa6fb8b",

  "favorite_numbers": "An array containing my all-time favorite numbers",
  "favorite_numbers": [19, 13, 53]
}

The above code is valid JSON. If you parse it, you'll get an object like this:

{
    "api_host": "hodorhodor.com",
    "retry_interval": 10,
    "auth_token": "5ad0eb93697215bc0d48a7b69aa6fb8b",
    "favorite_numbers": [19,13,53]
}

Which means there is no trace of the comments, and they won't have weird side-effects.

Happy hacking!


You can have comments in JSONP, but not in pure JSON. I've just spent an hour trying to make my program work with this example from Highcharts: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?

If you follow the link, you will see

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

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

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


The practical answer for Visual Studio Code users in 2019 is to use the 'jsonc' extension.

It is practical, because that is the extension recognized by Visual Studio Code to indicate "JSON with comments". Please let me know about other editors/IDEs in the comments below.

It would be nice if Visual Studio Code and other editors would add native support for JSON5 as well, but for now Visual Studio Code only includes support for 'jsonc'.

(I searched through all the answers before posting this and none mention 'jsonc'.)


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

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

import json, re

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

print(parse_json("""
{
  // This is a comment
  "name": "value" // so is this
  // "name": "value"
  // the above line gets removed
}
"""))

The practical answer for Visual Studio Code users in 2019 is to use the 'jsonc' extension.

It is practical, because that is the extension recognized by Visual Studio Code to indicate "JSON with comments". Please let me know about other editors/IDEs in the comments below.

It would be nice if Visual Studio Code and other editors would add native support for JSON5 as well, but for now Visual Studio Code only includes support for 'jsonc'.

(I searched through all the answers before posting this and none mention 'jsonc'.)


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.


No, JSON cannot have comments directly. However, as suggested by this, you can achieve a similar effect by doing something like

{
    "//name": "Name comment here",
    "name": "Jack",

    "//age": "Age comment here",
    "age": "25"
}

Most JSON parsers will ignore properties that are not mapped.


Not technically. But you can workaround as follows.

{
  "json": "actual data goes here, comments below",
  "comment1": "Lorem ipsum dolor sit amet",
  "comment2": "consectetur adipiscing elit"
}

Just put the comments in the data. If you number them to make each key path unique, you should have no problems.