Can json.loads ignore trailing commas?

后端 未结 4 1484
眼角桃花
眼角桃花 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:19

    In python you can have trailing commas inside of dictionaries and lists, so we should be able to take advantage of this using ast.literal_eval:

    import ast, json
    
    str = '{"key1": "value1", "key2": "value2",}'
    
    python_obj = ast.literal_eval(str) 
    # python_obj is {'key1': 'value1', 'key2': 'value2'}
    
    json_str = json.dumps(python_obj)
    # json_str is '{"key1": "value1", "key2": "value2"}'
    

    However, JSON isn't exactly python so there are a few edge cases to this. For example, values like null, true, false don't exist in python. We can replace those with valid python equivalents before we run the eval:

    import ast, json
    
    def clean_json(str):
      str = str.replace('null', 'None').replace('true', 'True').replace('false', 'False')
      return json.dumps(ast.literal_eval(str))
    

    This will unfortunately mangle any strings that have the words null, true, or false in them.

    {"sentence": "show your true colors"} 
    

    would become

    {"sentence": "show your True colors"}
    

提交回复
热议问题