Skip to main content
 首页 » 编程设计

python之如何使用 Python ijson 读取大型 JSON 文件

2025年01月19日952php

我正在尝试解析一个大的 json 文件(数百个演出)以从其 key 中提取信息。为简单起见,请考虑以下示例:

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) 

然后,我在 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, 

我期望检索列表中与 dic 键对应的所有数字。然而,我得到了

IncompleteJSONError: Incomplete JSON data

我知道这篇文章:Using python ijson to read a large json file with multiple json objects ,但在我的例子中,我有一个 json 文件,它格式正确,具有相对简单的架构。关于如何解析它的任何想法?谢谢。

请您参考如下方法:

ijson 有一个迭代器接口(interface)来处理大型 JSON 文件,允许延迟读取文件。您可以以小块的形式处理文件并将结果保存在其他地方。

调用 ijson.parse() 产生三个值 prefix, event, value

一些 JSON:

{ 
    "europe": [ 
      {"name": "Paris", "type": "city"}, 
      {"name": "Rhein", "type": "river"} 
    ] 
  } 

代码:

import ijson 
 
 
data = ijson.parse(open(FILE_PATH, 'r')) 
 
for prefix, event, value in data: 
    if event == 'string': 
        print(value) 

输出:

Paris 
city 
Rhein 
river 

引用:https://pypi.python.org/pypi/ijson