Can json.loads ignore trailing commas?

后端 未结 4 1496
眼角桃花
眼角桃花 2020-12-01 20:33

As mentioned in this StackOverflow question, you are not allowed to have any trailing commas in json. For example, this

{
    \"key1\": \"value1\",
    \"key         


        
4条回答
  •  一个人的身影
    2020-12-01 21:13

    Cobbling together the knowledge from a few other answers, especially the idea of using literal_eval from @Porkbutts answer, I present a wildly-evil solution to this problem

    def json_cleaner_loader(path):
        with open(path) as fh:
            exec("null=None;true=True;false=False;d={}".format(fh.read()))
        return locals()["d"]
    

    This works by defining the missing constants to be their Pythonic values before evaluating the JSON struct as Python code. The structure can then be accessed from locals() (which is yet another dictionary).

    This should work with both Python 2.7 and Python 3.x

    BEWARE this will execute whatever is in the passed file, which may do anything the Python interpreter can, so it should only ever be used on inputs which are known to be safe (ie. don't let web clients provide the content) and probably not in any production environment.
    This probably also fails if it's given a very large amount of content.

提交回复
热议问题