python - 如何从 Python 中的文件/流中懒惰地读取多个 JSON 值?

我想从 Python 中的文件/流中读取多个 JSON 对象,一次一个。不幸的是 json.load() 只是 .read() 直到文件结束;似乎没有任何方法可以使用它来读取单个对象或懒惰地迭代对象。

有没有办法做到这一点?使用标准库是理想的,但如果有第三方库,我会使用它。

目前我将每个对象放在单独的行上并使用 json.loads(f.readline()),但我真的不想这样做。

使用示例

example.py

import my_json as json
import sys

for o in json.iterload(sys.stdin):
    print("Working on a", type(o))

in.txt

{"foo": ["bar", "baz"]} 1 2 [] 4 5 6

示例 session

$ 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

最佳答案

JSON 通常不适合这种增量使用;没有标准的方法可以序列化多个对象,这样就可以轻松地一次加载一个对象,而无需解析整个对象。

您正在使用的每行对象解决方案也可以在其他地方看到。 Scrapy 称其为“JSON 行”:

  • https://docs.scrapy.org/en/latest/topics/exporters.html?highlight=exporters#jsonitemexporter
  • http://www.enricozini.org/2011/tips/python-stream-json/

你可以稍微用 Python 来做:

for jsonline in f:
    yield json.loads(jsonline)   # or do the processing in this loop

我认为这是最好的方法——它不依赖任何第三方库,而且很容易理解发生了什么。我也在自己的一些代码中使用过它。

https://stackoverflow.com/questions/6886283/

相关文章:

arrays - 数组可以是顶级 JSON 文本吗?

javascript - 如果名称包含点,如何获取对象值?

c# - 将 POST 中的 json 发送到 Web API 服务时出错

python - python中的json.dump()和json.dumps()有什么区别?

json - JSON中的反序列化和序列化是什么?

c# - Protocol Buffer 与 JSON 或 BSON

python - JSON 值错误 : Expecting property name: line

python - 如何使用 python 请求和处理 JSON?

javascript - 在 promise 链上使用 setTimeout

jquery - Rails 无法正确解码来自 jQuery 的 JSON(数组变成带有整数键的散列