Python 使用 json load 解析包含两个 json 对象列表的文件

Python to parse file with two lists of json objects using json load

我有一个很大的 json 文件,其中包含两个 json 对象列表。

示例数据:

data.json

[{"a":1}][{"b":2}]

parser.py

import json

message = json.load(open("data.json"))

for m in message:
    print m

不出所料,我得到了 ValueError。

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 290, in load
    **kw)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 369, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 10 - line 1 column 19 (char 9 - 18)

我想到了通过跟踪字符数来拆分文件。 处理这个问题的 pythonic 方法是什么?

您可以使用 json.JSONDecoder.raw_decode() 来解析一个完整的对象,并 return 它与它结束的字符位置,允许您遍历每个对象:

from json import JSONDecoder, JSONDecodeError

decoder = JSONDecoder()
data = '[{"a":1}][{"b":2}]'

pos = 0
while True:
    try:
        o, pos = decoder.raw_decode(data, pos)
        print(o)
    except JSONDecodeError:
        break

结果:

[{'a': 1}]
[{'b': 2}]