Ijson 是具有标准 Python 迭代器接口的迭代 JSON 解析器。
1 Installation
Ijson 托管在 PyPI 中,因此您应该能够通过 pip 安装它:
pip install ijson
为主要平台(Linux、MacOS、Windows)和 python 版本(2.7、3.5+)提供了二进制轮子。
2 Usage
所有使用示例都将使用描述地理对象的 JSON 文档:
{
"earth": {
"europe": [
{"name": "Paris", "type": "city", "info": { ... }},
{"name": "Thames", "type": "river", "info": { ... }},
// ...
],
"america": [
{"name": "Texas", "type": "state", "info": { ... }},
// ...
]
}
}
最常见的用法是让 ijson 从位于前缀下的 JSON 流中生成原生 Python 对象。
这是使用 items 函数完成的。以下是处理所有欧洲城市(city)的方法:
import ijson
f = urlopen('http://.../')
objects = ijson.items(f, 'earth.europe.item')
cities = (o for o in objects if o['type'] == 'city')
for city in cities:
do_something_with(city)
其他时候,迭代 对象成员而不是对象本身可能很有用(例如,当对象太大时)。在这种情况下,可以改用 kvitems 函数:
import ijson
f = urlopen('http://.../')
european_places = ijson.kvitems(f, 'earth.europe.item')
names = (v for k, v in european_places if k == 'name')
for name in names:
do_something_with(name)