Python json.loads shows ValueError: Extra data

后端 未结 9 811
甜味超标
甜味超标 2020-11-22 16:21

I am getting some data from a JSON file \"new.json\", and I want to filter some data and store it into a new JSON file. Here is my code:

import json
with ope         


        
9条回答
  •  太阳男子
    2020-11-22 16:34

    As you can see in the following example, json.loads (and json.load) does not decode multiple json object.

    >>> json.loads('{}')
    {}
    >>> json.loads('{}{}') # == json.loads(json.dumps({}) + json.dumps({}))
    Traceback (most recent call last):
      File "", line 1, in 
      File "C:\Python27\lib\json\__init__.py", line 338, in loads
        return _default_decoder.decode(s)
      File "C:\Python27\lib\json\decoder.py", line 368, in decode
        raise ValueError(errmsg("Extra data", s, end, len(s)))
    ValueError: Extra data: line 1 column 3 - line 1 column 5 (char 2 - 4)
    

    If you want to dump multiple dictionaries, wrap them in a list, dump the list (instead of dumping dictionaries multiple times)

    >>> dict1 = {}
    >>> dict2 = {}
    >>> json.dumps([dict1, dict2])
    '[{}, {}]'
    >>> json.loads(json.dumps([dict1, dict2]))
    [{}, {}]
    

提交回复
热议问题