Can comments be used in JSON?

后端 未结 30 1682
别跟我提以往
别跟我提以往 2020-11-22 02:16

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

30条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 02:48

    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.

提交回复
热议问题