Can comments be used in JSON?

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

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

30条回答
  •  庸人自扰
    2020-11-22 02:48

    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.

    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.

    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.

    ({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:

    {
      "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:

    {
        "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!

提交回复
热议问题