How to parse json file with c-style comments?

后端 未结 5 1341
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题