Can json.loads ignore trailing commas? Can json.loads ignore trailing commas? json json

Can json.loads ignore trailing commas?


Strip the commas before you pass the value in.

import redef clean_json(string):    string = re.sub(",[ \t\r\n]+}", "}", string)    string = re.sub(",[ \t\r\n]+\]", "]", string)    return string


You can wrap python's json parser with jsoncomment

JSON Comment allows to parse JSON files or strings with:

  • Single and Multi line comments
  • Multi line data strings
  • Trailing commas in objects and arrays, after the last item

Example usage:

import jsonfrom jsoncomment import JsonCommentwith open(filename) as data_file:        parser = JsonComment(json)    data = parser.load(data_file)


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, jsonstr = '{"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, jsondef 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"}