<p>我无法想象由其他程序自动创建的json文件会包含注释。因为<a href="http://www.json.org" rel="nofollow noreferrer">json spec</a>根本不定义注释,也就是<a href="https://plus.google.com/+DouglasCrockfordEsq/posts/RK8qyGVaGSr" rel="nofollow noreferrer">by design</a>,所以任何json库都不会输出带有注释的json文件。</p>
<p>这些评论通常是后来由人添加的。在这种情况下没有例外。这位专栏作家在他的文章中提到:<code>//"birthday": "nothing" //I comment this line</code>。</p>
<p>所以真正的问题应该是,如何正确地注释json文件中的某些内容,同时保持其与spec的兼容性,从而保持与其他json库的兼容性?</p>
<p>答案是,将字段重命名为另一个名称。示例:</p>
<pre><code>{
"foo": "content for foo",
"bar": "content for bar"
}
</code></pre>
<p>可以更改为:</p>
<pre><code>{
"foo": "content for foo",
"this_is_bar_but_been_commented_out": "content for bar"
}
</code></pre>
<p>这在大多数情况下都会很好地工作,因为使用者很可能会忽略意外字段(但并不总是如此,这取决于json文件使用者的实现)。所以YMMV.)</p>
<p><strong>更新</strong>:显然有些读者不满意,因为这个答案没有给出他们期望的“解决方案”。实际上,我确实给出了一个有效的解决方案,通过隐式链接到<a href="https://plus.google.com/+DouglasCrockfordEsq/posts/RK8qyGVaGSr" rel="nofollow noreferrer">JSON designer's quote</a>:</p>
<blockquote>
<p>Douglas Crockford Public Apr 30, 2012 Comments in JSON</p>
<p>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. </p>
<p>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.</p>
</blockquote>
<p>所以,是的,继续使用<a href="https://pypi.org/project/jsmin/" rel="nofollow noreferrer">JSMin</a>。请记住,当您走向“使用JSON中的注释”时,这是一个概念上未知的领域。不保证您选择的任何工具都能处理:inline<code>[1,2,3,/* a comment */ 10]</code>、Python样式<code>[1, 2, 3] # a comment</code>(这是Python中的注释,但不是Javascript中的注释)、INI样式<code>[1, 2, 3] ; a comment</code>,…,您就得到了这个想法。</p>
<p>我仍然建议首先不要在JSON中添加不符合的注释。</p>