JSON 中可以使用注释吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/244777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can comments be used in JSON?
提问by Michael Gundlach
Can I use comments inside a JSON file? If so, how?
我可以在 JSON 文件中使用注释吗?如果是这样,如何?
采纳答案by Eli
No.
不。
The JSON should all be data, and if you include a comment, then it will be data too.
JSON 应该都是数据,如果您包含注释,那么它也将是数据。
You could have a designated data element called "_comment"(or something) that would be ignored by apps that use the JSON data.
您可以指定一个名为"_comment"(或其他名称)的数据元素,该元素将被使用 JSON 数据的应用程序忽略。
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.
您可能最好在生成/接收 JSON 的过程中添加注释,因为他们应该提前知道 JSON 数据是什么,或者至少知道它的结构。
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"
}
}
}
}
}
回答by stakx - no longer contributing
No, comments of the form //…or /*…*/are not allowed in JSON. This answer is based on:
否,JSON 中不允许有表单的注释//…或/*…*/。这个答案基于:
- http://www.json.org
- RFC 4627:
The
application/jsonMedia Type for JavaScript Object Notation (JSON) - RFC 8259The JavaScript Object Notation (JSON) Data Interchange Format (supercedes RFCs 4627, 7158, 7159)
- http://www.json.org
- RFC 4627:
application/jsonJavaScript 对象表示法 (JSON)的媒体类型 - RFC 8259JavaScript 对象表示法 (JSON) 数据交换格式(取代 RFC 4627、7158、7159)
回答by Kyle Simpson
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.minify(),它从 JSON 块中去除注释和空格,并使其成为可以解析的有效 JSON。所以,你可以像这样使用它:
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:
当我发布它时,我得到了很多人甚至不同意它的想法的强烈反对,所以我决定写一篇关于为什么评论在 JSON 中有意义的综合博客文章。它包括来自 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
假设您使用 JSON 来保存要注释的配置文件。继续并插入您喜欢的所有评论。然后通过 JSMin 将其通过管道传递给您的 JSON 解析器。-道格拉斯·克罗克福德,2012 年
Hopefully that's helpful to those who disagree with why JSON.minify()could be useful.
希望这对那些不同意为什么JSON.minify()有用的人有所帮助。
回答by Artur Czajka
Comments were removed from JSON by design.
按照设计从 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.
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.
我从 JSON 中删除了注释,因为我看到人们使用它们来保存解析指令,这种做法会破坏互操作性。我知道缺乏评论会让一些人感到难过,但事实并非如此。
假设您使用 JSON 来保存要注释的配置文件。继续并插入您喜欢的所有评论。然后通过 JSMin 将其通过管道传递给您的 JSON 解析器。
回答by p3drosola
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.
正如已经指出的那样,这个 hack 利用了规范的实现。并非所有 JSON 解析器都能理解这种 JSON。流解析器尤其会阻塞。
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.
我发现了一个小技巧,它允许您将注释放在 JSON 文件中,而不会影响解析,也不会以任何方式改变所表示的数据。
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.
似乎在声明对象文字时,您可以使用相同的键指定两个值,最后一个优先。信不信由你,事实证明 JSON 解析器的工作方式是一样的。因此,我们可以使用它在源 JSON 中创建注释,这些注释不会出现在已解析的对象表示中。
({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:
如果我们应用此技术,您的注释 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]
}
The above code is valid JSON. If you parse it, you'll get an object like this:
上面的代码是有效的 JSON。如果你解析它,你会得到一个这样的对象:
{
"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!
快乐黑客!
回答by laktak
JSON does not support comments. It was also never intended to be used for configuration files where comments would be needed.
JSON 不支持注释。它也从未打算用于需要注释的配置文件。
Hjson is a configuration file format for humans. Relaxed syntax, fewer mistakes, more comments.
Hjson 是一种供人类使用的配置文件格式。宽松的语法,更少的错误,更多的评论。
See hjson.orgfor JavaScript, Java, Python, PHP, Rust, Go, Ruby and C# libraries.
有关JavaScript、Java、Python、PHP、Rust、Go、Ruby 和 C# 库,请参阅hjson.org。
回答by Marnen Laibow-Koser
Consider using YAML. It's nearly a superset of JSON (virtually all valid JSON is valid YAML) and it allows comments.
考虑使用 YAML。它几乎是 JSON 的超集(几乎所有有效的 JSON 都是有效的 YAML)并且它允许注释。
回答by Cheery
You can't. At least that's my experience from a quick glance at json.org.
你不能。至少这是我快速浏览json.org 的经验。
JSON has its syntax visualized on that page. There isn't any note about comments.
JSON 的语法在该页面上可视化。没有任何关于评论的注释。
回答by schoetbi
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:
注释不是官方标准,尽管一些解析器支持 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 }
}
jsonlintdoes not validate this. So comments are a parser specific extension and not standard.
jsonlint不验证这一点。所以注释是解析器特定的扩展而不是标准的。
Another parser is JSON5.
另一个解析器是JSON5。
An alternative to JSON TOML.
JSON TOML的替代方案。
A further alternative is jsonc.
另一种选择是jsonc。
回答by raffel
You should write a JSON schemainstead. JSON schema is currently a proposed Internet draft specification. Besides documentation, the schema can also be used for validating your JSON data.
您应该改为编写JSON 模式。JSON 模式目前是一个提议的 Internet 草案规范。除了文档之外,模式还可以用于验证您的 JSON 数据。
Example:
例子:
{
"description":"A person",
"type":"object",
"properties":
{
"name":
{
"type":"string"
},
"age":
{
"type":"integer",
"maximum":125
}
}
}
You can provide documentation by using the descriptionschema attribute.
您可以使用description架构属性提供文档。


