How to parse json file with c-style comments?

后端 未结 5 1317
無奈伤痛
無奈伤痛 2020-12-03 10:19

I have a json file, such as the following:

    { 
       \"author\":\"John\",
       \"desc\": \"If it is important to decode all valid JSON correctly \\ 
an         


        
相关标签:
5条回答
  • 2020-12-03 10:21

    How about commentjson?

    http://commentjson.readthedocs.io/en/latest/

    This can parse something like below.

    {
        "name": "Vaidik Kapoor", # Person's name
        "location": "Delhi, India", // Person's location
    
        # Section contains info about
        // person's appearance
        "appearance": {
            "hair_color": "black",
            "eyes_color": "black",
            "height": "6"
        }
    }
    

    Likely elasticsearch, some products' REST API do not accept comment field. Therefore, I think comment inside json is necessary for a client in order to maintain such as a json template.


    EDITED

    jsmin seems to be more common.

    https://pypi.python.org/pypi/jsmin

    • references
      • https://plus.google.com/+DouglasCrockfordEsq/posts/RK8qyGVaGSr
      • Can comments be used in JSON?
      • https://www.quora.com/How-do-I-write-comments-inside-a-JSON-document
      • https://github.com/JetBrains/intellij-community/blob/webstorm/191.6183.63/json/src/com/intellij/json/JsonBundle.properties#L16
    0 讨论(0)
  • 2020-12-03 10:23

    jsoncomment is good, but inline comment is not supported.

    Check out jstyleson, which support

    • inline comment
    • single-line comment
    • multi-line comment
    • trailing comma.

    Example

    Install

    pip install jstyleson

    Usage

    import jstyleson
    result_dict = jstyleson.loads(invalid_json_str) # OK
    jstyleson.dumps(result_dict)
    
    0 讨论(0)
  • 2020-12-03 10:42

    I have not personally used it, but the jsoncomment python package supports parsing a JSON file with comments.

    You use it in place of the JSON parser as follows:

    parser = JsonComment(json)
    parsed_object = parser.loads(jsonString)
    
    0 讨论(0)
  • 2020-12-03 10:46

    I can not imagine a json file "auto created by other program" would contain comments inside. Because json spec defines no comment at all, and that is by design, so no json library would output a json file with comment.

    Those comments are usually added later, by a human. No exception in this case. The OP mentioned that in his post: //"birthday": "nothing" //I comment this line.

    So the real question should be, how do I properly comment some content in a json file, yet maintaining its compliance with spec and hence its compatibility with other json libraries?

    And the answer is, rename your field to another name. Example:

    {
        "foo": "content for foo",
        "bar": "content for bar"
    }
    

    can be changed into:

    {
        "foo": "content for foo",
        "this_is_bar_but_been_commented_out": "content for bar"
    }
    

    This will work just fine most of the time because the consumer will very likely ignore unexpected fields (but not always, it depends on your json file consumer's implementation. So YMMV.)

    UPDATE: Apparently some reader was unhappy because this answer does not give the "solution" they expect. Well, in fact, I did give a working solution, by implicitly linking to the JSON designer's quote:

    Douglas Crockford Public Apr 30, 2012 Comments in 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.

    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.

    So, yeah, go ahead to use JSMin. Just keep in mind that when you are heading towards "using comments in JSON", that is a conceptually uncharted territory. There is no guarantee that whatever tools you choose would handle: inline [1,2,3,/* a comment */ 10], Python style [1, 2, 3] # a comment (which is a comment in Python but not in Javascript), INI style [1, 2, 3] ; a comment, ..., you get the idea.

    I would still suggest to NOT adding noncompliant comments in JSON in the first place.

    0 讨论(0)
  • 2020-12-03 10:46

    If you are like me who prefers avoiding external libraries, this function I wrote will read json from a file and remove "//" and "/* */" type comments:

    def GetJsonFromFile(filePath):
        contents = ""
        fh = open(filePath)
        for line in fh:
            cleanedLine = line.split("//", 1)[0]
            if len(cleanedLine) > 0 and line.endswith("\n") and "\n" not in cleanedLine:
                cleanedLine += "\n"
            contents += cleanedLine
        fh.close
        while "/*" in contents:
            preComment, postComment = contents.split("/*", 1)
            contents = preComment + postComment.split("*/", 1)[1]
        return contents
    

    Limitations: As David F. brought up in the comments, this will break beautifully (ie: horribly) with // and /* inside string literals. Would need to write some code around it if you want to support //, /*, */ within your json string contents.

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