我无法想象json文件"auto created by other program"会包含注释.因为json spec完全不定义注释,也就是by design,所以没有json库会输出带有注释的json文件.
这些 comments 通常是稍后由人添加的.在这种情况下也不例外.操作员在他的帖子中提到了这一点://"birthday": "nothing" //I comment this line
.
So the real question should be, how do I properly comment some content in a json file, yet maintaining its compliance with spec and hence its compatibility with other json libraries?
答案是,将您的字段重命名为另一个名称.示例:
{
"foo": "content for foo",
"bar": "content for bar"
}
可以更改为:
{
"foo": "content for foo",
"this_is_bar_but_been_commented_out": "content for bar"
}
This will work just fine most of the time because the consumer will very likely ignore unexpected fields (but not always, it depends on your json file consumer's implementation. So YMMV.)
UPDATE:显然,一些读者不高兴,因为这个答案没有给出他们期望的"解决方案".事实上,我确实给出了一个有效的解决方案,通过隐式链接到JSON designer's quote:
Douglas Crockford Public Apr 30, 2012 Comments in 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.
So, yeah, go ahead to use JSMin. Just keep in mind that when you are heading towards "using comments in JSON", that is a conceptually uncharted territory. There is no guarantee that whatever tools you choose would handle: inline [1,2,3,/* a comment */ 10]
, Python style [1, 2, 3] # a comment
(which is a comment in Python but not in Javascript), INI style [1, 2, 3] ; a comment
, ..., you get the idea.
我仍然建议首先不要在JSON中添加不一致的注释.