Can comments be used in JSON?

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

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

相关标签:
30条回答
  • 2020-11-22 02:26

    You should write a JSON schema instead. JSON schema is currently a proposed Internet draft specification. Besides documentation, the schema can also be used for validating your JSON data.

    Example:

    {
        "description":"A person",
        "type":"object",
        "properties":
            {
                "name":
                    {
                        "type":"string"
                    },
                "age":
                    {
                        "type":"integer",
                        "maximum":125
                    }
            }
    }
    

    You can provide documentation by using the description schema attribute.

    0 讨论(0)
  • 2020-11-22 02:26

    It depends on your JSON library. Json.NET supports JavaScript-style comments, /* commment */.

    See another Stack Overflow question.

    0 讨论(0)
  • 2020-11-22 02:27

    The Dojo Toolkit JavaScript toolkit (at least as of version 1.4), allows you to include comments in your JSON. The comments can be of /* */ format. Dojo Toolkit consumes the JSON via the dojo.xhrGet() call.

    Other JavaScript toolkits may work similarly.

    This can be helpful when experimenting with alternate data structures (or even data lists) before choosing a final option.

    0 讨论(0)
  • 2020-11-22 02:28

    Comments are not an official standard, although some parsers support C++-style comments. One that I use is JsonCpp. In the examples there is this one:

    // Configuration options
    {
        // Default encoding for text
        "encoding" : "UTF-8",
    
        // Plug-ins loaded at start-up
        "plug-ins" : [
            "python",
            "c++",
            "ruby"
            ],
    
        // Tab indent size
        "indent" : { "length" : 3, "use_space": true }
    }
    

    jsonlint does not validate this. So comments are a parser specific extension and not standard.

    Another parser is JSON5.

    An alternative to JSON TOML.

    A further alternative is jsonc.

    The latest version of nlohmann/json has optional support for ignoring comments on parsing.

    0 讨论(0)
  • 2020-11-22 02:30

    In my case, I need to use comments for debug purposes right before the output of the JSON structure. So I decided to use debug information in the HTTP header, to avoid breaking the client:

    header("My-Json-Comment: Yes, I know it's a workaround ;-) ");
    

    0 讨论(0)
  • 2020-11-22 02:32

    To cut a JSON item into parts I add "dummy comment" lines:

    {
    
    "#############################" : "Part1",
    
    "data1"             : "value1",
    "data2"             : "value2",
    
    "#############################" : "Part2",
    
    "data4"             : "value3",
    "data3"             : "value4"
    
    }
    
    0 讨论(0)
提交回复
热议问题