Can comments be used in JSON?

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

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

30条回答
  •  情话喂你
    2020-11-22 02:37

    JSON makes a lot of sense for config files and other local usage because it's ubiquitous and because it's much simpler than XML.

    If people have strong reasons against having comments in JSON when communicating data (whether valid or not), then possibly JSON could be split into two:

    • JSON-COM: JSON on the wire, or rules that apply when communicating JSON data.
    • JSON-DOC: JSON document, or JSON in files or locally. Rules that define a valid JSON document.

    JSON-DOC will allow comments, and other minor differences might exist such as handling whitespace. Parsers can easily convert from one spec to the other.

    With regards to the remark made by Douglas Crockford on this issues (referenced by @Artur Czajka)

    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.

    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!

提交回复
热议问题