我希望从 Python 中的文件/流中读取多个 JSON 对象,一次一个。不幸的是,在文件结束之前,json.load()
只是 .read()
; 似乎没有任何方法可以使用它来读取单个对象或对对象进行延迟迭代。
Is there any way to do this? Using the standard library would be ideal, but if there's a third-party library I'd use that instead.
目前,我把每个对象放在一个单独的行,并使用 json.loads(f.readline())
,但我真的希望不需要这样做。
import my_json as json
import sys
for o in json.iterload(sys.stdin):
print("Working on a", type(o))
{"foo": ["bar", "baz"]} 1 2 [] 4 5 6
$ python3.2 example.py < in.txt
Working on a dict
Working on a int
Working on a int
Working on a list
Working on a int
Working on a int
Working on a int