Pau*_*aul 5 python json python-2.7 ijson
我正在尝试解析一个大的 json 文件(数百个演出)以从其密钥中提取信息。为简单起见,请考虑以下示例:
import random, string
# To create a random key
def random_string(length):
return "".join(random.choice(string.lowercase) for i in range(length))
# Create the dicitonary
dummy = {random_string(10): random.sample(range(1, 1000), 10) for times in range(15)}
# Dump the dictionary into a json file
with open("dummy.json", "w") as fp:
json.dump(dummy, fp)
Run Code Online (Sandbox Code Playgroud)
然后,我在 python 2.7 中使用 ijson 来解析文件:
file_name = "dummy.json"
with open(file_name, "r") as fp:
for key in dummy.keys():
print "key: ", key
parser = ijson.items(fp, str(key) + ".item")
for number in parser:
print number,
Run Code Online (Sandbox Code Playgroud)
我期待检索与 dic 键对应的列表中的所有数字。然而,我得到了
IncompleteJSONError: 不完整的 JSON 数据
我知道这篇文章:Using python ijson to read a large json file with multiple json objects,但在我的情况下,我有一个格式良好的json文件,具有相对简单的架构。关于如何解析它的任何想法?谢谢你。
ijson有一个迭代器接口来处理大型 JSON 文件,允许懒惰地读取文件。您可以以小块的形式处理文件并将结果保存在其他地方。
调用ijson.parse()产生三个值prefix, event, value
一些JSON:
{
"europe": [
{"name": "Paris", "type": "city"},
{"name": "Rhein", "type": "river"}
]
}
Run Code Online (Sandbox Code Playgroud)
代码:
import ijson
data = ijson.parse(open(FILE_PATH, 'r'))
for prefix, event, value in data:
if event == 'string':
print(value)
Run Code Online (Sandbox Code Playgroud)
输出:
Paris
city
Rhein
river
Run Code Online (Sandbox Code Playgroud)
参考:https : //pypi.python.org/pypi/ijson
| 归档时间: |
|
| 查看次数: |
12408 次 |
| 最近记录: |