可以在JSON中使用注释吗?

我可以在JSON文件中使用注释吗? 如果是这样,怎么样?

我不相信你可以有实际的评论。 JSON应该都是数据,如果包含注释,那么它也将是数据。

您可以使用名为"_comment" (或其他)的指定数据元素,这些元素将被使用JSON数据的应用程序忽略。

在生成/接收JSON的过程中,您可能会更好地评论它们,因为它们应该知道JSON数据将提前发生什么,或者至少是它的结构。

但是,如果您决定:

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

,JSON中不允许使用/*…*/ //…/*…*/格式的注释。 这个答案是基于:

  • http://www.json.org
  • RFC 4627 :用于JavaScript对象表示法(JSON)的application/json媒体类型
  • RFC 7159 JavaScript对象表示法(JSON)数据交换格式 – 废止时间:4627,7158

包括评论,如果你选择; 在解析或传输之前,用缩小器去除它们。

我刚刚发布了JSON.minify() ,它从JSON块中删除注释和空白,并使其有效的可以解析的JSON。 所以,你可以像这样使用它:

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

当我发布它的时候,我对这个想法产生了巨大的反应,所以我决定写一篇全面的博客文章,为什么评论在JSON中是有意义的 。 它包括来自JSON创建者的这个值得注意的评论:

假设您使用JSON来保存您想要注释的配置文件。 继续,插入你喜欢的所有评论。 然后通过JSMin管理它,然后把它交给你的JSON解析器。 – 道格拉斯·克罗克福德,2012

希望对那些不同意为什么JSON.minify()可能有用的人有帮助。

评论从设计中删除了JSON。

我从JSON中删除了评论,因为我看到有人用它们来保存解析指令,这种做法会破坏互操作性。 我知道缺乏评论会让一些人伤心,但不应该。

假设您使用JSON来保存您想要注释的配置文件。 继续,插入你喜欢的所有评论。 然后通过JSMin管理它,然后把它交给你的JSON解析器。

来源: Douglas Crockford在G +上的公开声明

免责声明:您的担保是无效的

正如已经指出的那样,这个黑客利用规范的实现。 并不是所有的JSON解析器都能理解这种JSON。 流式解析器尤其会窒息。

这是一个有趣的好奇心,但是你根本不应该用它做任何事情 。 以下是原来的答案。


我发现了一些小技巧,允许您将注释放置在不会影响解析的JSON文件中,或者以任何方式更改所表示的数据。

看来在声明一个对象字面值的时候,你可以用同一个键指定两个值,而最后一个优先。 相信与否,事实证明,JSON解析器以相同的方式工作。 所以我们可以使用它来创建源代码JSON中的注释,这些注释不会出现在解析对象表示中。

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

如果我们应用这种技术,您的评论JSON文件可能如下所示:

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

上面的代码是有效的JSON 。 如果你解析它,你会得到这样一个对象:

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

这意味着没有任何评论的痕迹,他们不会有奇怪的副作用。

快乐的黑客!

JSON不支持评论。 这也从来没有打算被用于需要评论的配置文件。

Hjson是一个用于人类的配置文件格式。 轻松的语法,更少的错误,更多的评论。

Hjson介绍

有关JavaScript,Java,Python,PHP,Rust,Go,Ruby和C#库,请参阅hjson.org 。

你不能。 至少这是我的快速浏览json.org的经验。

JSON的语法在该页面上可视化。 没有关于评论的任何说明。

考虑使用YAML。 这几乎是JSON的超集(几乎所有有效的JSON都是有效的YAML),它允许评论。

你应该写一个JSON模式 。 JSON模式是目前提出的Internet草案规范。 除了文档,模式也可以用于验证您的JSON数据。

例:

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

您可以使用description schema属性来提供文档。

评论不是官方的标准。 尽管一些解析器支持C风格的注释。 我使用的是JsonCpp 。 在这个例子中有这个:

 // 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不验证这一点。 所以注释是一个解析器特定的扩展,而不是标准的。

另一个解析器是JSON5 。

JSON TOML的替代方案。

如果你使用Jackson作为你的JSON解析器,那么这是你如何启用它来允许评论:

 ObjectMapper mapper = new ObjectMapper().configure(Feature.ALLOW_COMMENTS, true); 

那么你可以有这样的评论:

 { key: "value" // comment } 

你也可以通过设置#开头的评论:

 mapper.configure(Feature.ALLOW_YAML_COMMENTS, true); 

但一般来说(如之前所回答的)规范不允许评论。

抱歉,我们无法在JSON中使用注释…请参阅JSON.org上的 JSON语法图。

道格拉斯·克罗克福德(Douglas Crockford)表示:

我从JSON中删除了评论,因为我看到有人用它们来保存解析指令,这种做法会破坏互操作性。 我知道缺乏评论会让一些人伤心,但不应该。

假设您使用JSON来保存您想要注释的配置文件。 继续,插入你喜欢的所有评论。 然后通过JSMin管理它,然后把它交给你的JSON解析器。

如果你的文本文件(这是一个JSON字符串)将被某个程序读取,那么在使用它之前剥离C或C ++风格的注释是多么困难?

答:这将是一个班轮。 如果你这样做,那么JSON文件可以用作配置文件。

JSON本身不支持注释,但是你可以让你自己的解码器或者至少预处理器去除注释,这是非常好的(只要你忽略注释,不要用它来指导你的应用程序应该如何处理JSON数据)。

JSON没有评论。 JSON编码器不能输出注释。 一个JSON解码器可以接受和忽略注释。

永远不要用评论来传递任何有意义的东西。 这就是JSON的用途。

Cf: JSON规范的作者Douglas Crockford 。

我只是遇到这个配置文件。 我不想使用XML (冗长,图形,丑陋,难以阅读),或“ini”格式(没有层次结构,没有真正的标准等)或Java“属性”格式(如.ini)。

JSON可以做所有他们可以做的事情,但它不那么冗长,而且可读性更强 – 而且分析器很容易,而且在很多语言中都是无处不在的。 这只是一个数据树。 但是带外注释经常需要记录“默认”配置等。 配置永远不会是“完整的文档”,而是保存的数据树,在需要时可以被人类读取。

我想可以使用"#": "comment" ,为“有效的”JSON。

JSON背后的想法是在应用程序之间提供简单的数据交换。 这些通常是基于Web的,而语言是JavaScript。

它并不真正允许这样的注释,但是,将一个注释作为数据中的名称/值对之一传递肯定会起作用,尽管这些数据显然需要被解析代码忽略或专门处理。

所有这一切,并不是意味着JSON文件应该包含传统意义上的评论。 它应该只是数据。

看看JSON网站了解更多细节。

如果您在ASP.NET中使用Newtonsoft.Json库来读取/反序列化,则可以在JSON内容中使用注释:

//“name”:“string”

//“id”:int

要么

/* 这是一个

评论示例* /

PS:单行注释仅支持6个以上版本的Newtonsoft Json。

对于无法想到的人来说,还有其他一些注意事项:我在我制作的ASP.NET Web应用程序中使用JSON格式进行基本设置。 我读取该文件,将其转换为Newtonsoft库的设置对象,并在必要时使用它。

我更喜欢在JSON文件本身中编写关于每个单独设置的注释,只要我使用的库是可以的,我真的不关心JSON格式的完整性。

我认为这是一个“易于使用/理解”的方式,而不是创建一个单独的“settings.README”文件并解释其中的设置。

如果你有这种用法的问题, 对不起,精灵在灯外。 人们会发现JSON格式的其他用法,并且没有什么可以做的。

以下是我在Google Firebase文档中找到的内容 ,您可以使用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" } 

这取决于你的JSON库。 Json.NET支持JavaScript风格的注释, /* commment */

看到另一个堆栈溢出问题 。

JSON对配置文件和其他本地用法有很大的意义,因为它是无处不在的,因为它比XML简单得多。

如果人们在传递数据(无论是否有效)时有强烈的反对JSON评论的理由,那么JSON可能会被分成两部分:

  • JSON-COM:连线上的JSON,或传送JSON数据时应用的规则。
  • JSON-DOC:JSON文档或JSON文件或本地。 定义有效的JSON文档的规则。

JSON-DOC将允许注释,并且可能存在其他细微差异,例如处理空白。 解析器可以很容易地从一个规范转换到另一个规范。

关于道格拉斯·克罗克福德(Douglas Crockford)对这个问题所作的评论 (引用@Artur Czajka)

假设您使用JSON来保存您想要注释的配置文件。 继续,插入你喜欢的所有评论。 然后通过JSMin管它,然后把它交给你的JSON解析器。

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!

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.

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.

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. 随你便。

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

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

There is a good solution (hack), which is valid JSON. Just make the same key twice (or more). 例如:

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

So JSON will understand this as:

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

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

 { "#############################" : "Part1", "data1" : "value1", "data2" : "value2", "#############################" : "Part2", "data4" : "value3", "data3" : "value4" } 

The author of JSON wants us to include comments in the JSON, but strip them out before parsing them (see link provided by Michael Burr.) If JSON should have comments, why not standardize them, and let the JSON parser do the job? I don't agree with the logic there, but, alas, that's the standard. Using YAML solution as suggested by others is good, but requires library dependency.

If you want to strip out comments, but don't want to have a library dependency, here is a two-line solution, which works for C++-style comments, but can be adapted to others:

 var comments=new RegExp("//.*", 'mg'); data = JSON.parse(fs.readFileSync(sample_file, 'utf8').replace(comments, '')); 

Note that this solution can only be used in cases where you can be sure that the JSON data does not contain the comment initiator, eg ('//').

Another way to achieve JSON parsing, stripping of comments, and no extra library, is to evaluate the JSON in a JS interpreter. The caveat with that approach, of course, is that you would only want to evaluate untainted data (no untrusted user-input.) Here is an example of this approach in node.js — another caveat, following example will only read the data once and then it will be cached:

 data = require(fs.realpathSync(doctree_fp)); 

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

You can use decomment library for that. Below is a complete example.

Input JSON (file input.js):

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

Test Application:

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

输出:

 { value: 123 } 

See also: gulp-decomment , grunt-decomment