Can json.loads ignore trailing commas?
json, python, python-2.7
Solution
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 json
from jsoncomment import JsonComment
with open(filename) as data_file:
parser = JsonComment(json)
data = parser.load(data_file)
Problem
As mentioned in this StackOverflow question, you are not allowed to have any trailing commas in json. For example, this ``` { "key1": "value1", "key2": "value2" } ``` is fine, but this ``` { "key1": "value1", "key2": "value2", } ``` is invalid syntax. For reasons mentioned in this other StackOverflow question, using a trailing comma is legal (and perhaps encouraged?) in Python code. I am working with both Python and JSON, so I would love to be able to be consistent across both types of files. Is there a way to have `json.loads` ignore trailing commas?