Can comments be used in JSON?

后端 未结 30 1508
别跟我提以往
别跟我提以往 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.

    0 讨论(0)
  • 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!

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

    I just encountering this for configuration files. I don't want to use XML (verbose, graphically, ugly, hard to read), or "ini" format (no hierarchy, no real standard, etc.) or Java "Properties" format (like .ini).

    JSON can do all they can do, but it is way less verbose and more human readable - and parsers are easy and ubiquitous in many languages. It's just a tree of data. But out-of-band comments are a necessity often to document "default" configurations and the like. Configurations are never to be "full documents", but trees of saved data that can be human readable when needed.

    I guess one could use "#": "comment", for "valid" JSON.

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

    NO. JSON used to support comments, but they were abused and removed from the standard.

    From the creator of 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. - Douglas Crockford, 2012

    The official JSON site is at JSON.org. JSON is defined as a standard by ECMA International. There is always a petition process to have standards revised. It is unlikely that annotations will be added to the JSON standard for several reasons.

    JSON by design is an easily reverse-engineered (human parsed) alternative to XML. It is simplified even to the point that annotations are unnecessary. It is not even a markup language. The goal is stability and interoperablilty.

    Anyone who understands the "has-a" relationship of object orientation can understand any JSON structure - that is the whole point. It is just a directed acyclic graph (DAG) with node tags (key/value pairs), which is a near universal data structure.

    This only annotation required might be "//These are DAG tags". The key names can be as informative as required, allowing arbitrary semantic arity.

    Any platform can parse JSON with just a few lines of code. XML requires complex OO libraries that are not viable on many platforms.

    Annotations would just make JSON make less interoperable. There is simply nothing else to add, unless what you really need is a markup language (XML), and don't care if your persisted data is easily parsed.

    BUT as the creator of JSON also observed, there has always been JS pipeline support for comments:

    Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser. - Douglas Crockford, 2012

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

    JSON doesn't allow comments, per se. The reasoning is utterly foolish, because you can use JSON itself to create comments, which obviates the reasoning entirely, and loads the parser data space for no good reason at all for exactly the same result and potential issues, such as they are: a JSON file with comments.

    If you try to put comments in (using // or /* */ or # for instance), then some parsers will fail because this is strictly not within the JSON specification. So you should never do that.

    Here, for instance, where my image manipulation system has saved image notations and some basic formatted (comment) information relating to them (at the bottom):

    {
        "Notations": [
            {
                "anchorX": 333,
                "anchorY": 265,
                "areaMode": "Ellipse",
                "extentX": 356,
                "extentY": 294,
                "opacity": 0.5,
                "text": "Elliptical area on top",
                "textX": 333,
                "textY": 265,
                "title": "Notation 1"
            },
            {
                "anchorX": 87,
                "anchorY": 385,
                "areaMode": "Rectangle",
                "extentX": 109,
                "extentY": 412,
                "opacity": 0.5,
                "text": "Rect area\non bottom",
                "textX": 98,
                "textY": 385,
                "title": "Notation 2"
            },
            {
                "anchorX": 69,
                "anchorY": 104,
                "areaMode": "Polygon",
                "extentX": 102,
                "extentY": 136,
                "opacity": 0.5,
                "pointList": [
                    {
                        "i": 0,
                        "x": 83,
                        "y": 104
                    },
                    {
                        "i": 1,
                        "x": 69,
                        "y": 136
                    },
                    {
                        "i": 2,
                        "x": 102,
                        "y": 132
                    },
                    {
                        "i": 3,
                        "x": 83,
                        "y": 104
                    }
                ],
                "text": "Simple polygon",
                "textX": 85,
                "textY": 104,
                "title": "Notation 3"
            }
        ],
        "imageXW": 512,
        "imageYW": 512,
        "imageName": "lena_std.ato",
        "tinyDocs": {
            "c01": "JSON image notation data:",
            "c02": "-------------------------",
            "c03": "",
            "c04": "This data contains image notations and related area",
            "c05": "selection information that provides a means for an",
            "c06": "image gallery to display notations with elliptical,",
            "c07": "rectangular, polygonal or freehand area indications",
            "c08": "over an image displayed to a gallery visitor.",
            "c09": "",
            "c10": "X and Y positions are all in image space. The image",
            "c11": "resolution is given as imageXW and imageYW, which",
            "c12": "you use to scale the notation areas to their proper",
            "c13": "locations and sizes for your display of the image,",
            "c14": "regardless of scale.",
            "c15": "",
            "c16": "For Ellipses, anchor is the  center of the ellipse,",
            "c17": "and the extents are the X and Y radii respectively.",
            "c18": "",
            "c19": "For Rectangles, the anchor is the top left and the",
            "c20": "extents are the bottom right.",
            "c21": "",
            "c22": "For Freehand and Polygon area modes, the pointList",
            "c23": "contains a series of numbered XY points. If the area",
            "c24": "is closed, the last point will be the same as the",
            "c25": "first, so all you have to be concerned with is drawing",
            "c26": "lines between the points in the list. Anchor and extent",
            "c27": "are set to the top left and bottom right of the indicated",
            "c28": "region, and can be used as a simplistic rectangular",
            "c29": "detect for the mouse hover position over these types",
            "c30": "of areas.",
            "c31": "",
            "c32": "The textx and texty positions provide basic positioning",
            "c33": "information to help you locate the text information",
            "c34": "in a reasonable location associated with the area",
            "c35": "indication.",
            "c36": "",
            "c37": "Opacity is a value between 0 and 1, where .5 represents",
            "c38": "a 50% opaque backdrop and 1.0 represents a fully opaque",
            "c39": "backdrop. Recommendation is that regions be drawn",
            "c40": "only if the user hovers the pointer over the image,",
            "c41": "and that the text associated with the regions be drawn",
            "c42": "only if the user hovers the pointer over the indicated",
            "c43": "region."
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:53

    If your text file, which is a JSON string, is going to be read by some program, how difficult would it be to strip out either C or C++ style comments before using it?

    Answer: It would be a one liner. If you do that then JSON files could be used as configuration files.

    0 讨论(0)
提交回复
热议问题