Python can't parse JSON with extra trailing comma

前端 未结 6 895
梦如初夏
梦如初夏 2020-12-21 03:59

This code:

import json
s = \'{ \"key1\": \"value1\", \"key2\": \"value2\", }\'
json.loads(s)

produces this error in Python 2:

6条回答
  •  春和景丽
    2020-12-21 04:25

    It could be that this data stream is JSON5, in which case there's a parser for that: https://pypi.org/project/json5/

    This situation can be alleviated by a regex substitution that looks for ", }, and replaces it with " }, allowing for any amount of whitespace between the quotes, comma and close-curly.

    >>> import re
    >>> s = '{ "key1": "value1", "key2": "value2", }'
    >>> re.sub(r"\"\s*,\s*\}", "\" }", s)
    '{ "key1": "value1", "key2": "value2" }'
    

    Giving:

    >>> import json
    >>> s2 = re.sub(r"\"\s*,\s*\}", "\" }", s)
    >>> json.loads(s2)
    {'key1': 'value1', 'key2': 'value2'}
    

    EDIT: as commented, this is not a good practice unless you are confident your JSON data contains only simple words, and this change is not corrupting the data-stream further. As I commented on the OP, the best course of action is to repair the up-stream data source. But sometimes that's not possible.

提交回复
热议问题