如何处理巨大的 JSON 文件?

How to handle huge JSON files?

我的 JSON 文件是 5.5 MB(对象检测模型的 Object365 数据集的注释文件)。我的 Python 程序甚至无法将其作为简单的文本文件读取。

 def ob365_converter(inputJsonFile, datasetPath):
    text = readFileLine(inputJsonFile)
    print("text:")
    print(text[0:100])
    datasetJson = json.loads(text)
    print("dataset loaded")
    for item in datasetJson["annotations"]:
        #Do some operations
        . . .
 
    def readFileLine(filePath):
        p = Path(filePath)
        if not p.is_file():
            print("%s is not a file", filePath)
            return ""
        with open(filePath, "r") as f:
            text = f.readline()
        return text

输出甚至不显示第一条消息“文本:”。我也尝试了以下相同的结果:

print ("A")
f = open(inputJsonFile, 'r')
datasetJson = json.load(f)
f.close()
print ("B")

如何处理 Python 中巨大的 JSON 文件?

json 文件的大尺寸需要处理太多源。正如@cizario 的 link 中所述,应该使用一些流逻辑来访问 json 对象而不存储文件的所有内容。

可以在 https://www.npmjs.com/package/stream-json

找到一个在流中工作的 py 库