在 Python 中加载大型 JSON 列表的最佳方法是什么?

Sam*_*dio 4 python json large-files

我可以访问一组文件(每个文件大约 80-800mb)。不幸的是,每个文件中只有一行。该行只包含一个 JSON 对象(一个列表列表)。将其加载并解析为较小的 JSON 对象的最佳方法是什么?

Vin*_*ceP 7

该模块pandas 0.21.0现在支持 chunksize 作为read_json. 您可以一次加载和操作一个块:

import pandas as pd
chunks = pd.read_json(file, lines=True, chunksize = 100)
for c in chunks:
    print(c)
Run Code Online (Sandbox Code Playgroud)


Cha*_*guy 6

这里已经有一个类似的帖子。这是他们提出的解决方案:

import json
with open('file.json') as infile:
  o = json.load(infile)
  chunkSize = 1000
  for i in xrange(0, len(o), chunkSize):
    with open('file_' + str(i//chunkSize) + '.json', 'w') as outfile:
      json.dump(o[i:i+chunkSize], outfile)
Run Code Online (Sandbox Code Playgroud)

  • 被杀了,这就是python shell所说的 (2认同)
  • 问题要求*“加载并将其解析为较小的 JSON 对象”*,而不是*“转储到一个输出文件”*。在这里,您只是将原始 JSON 输入拆分为固定长度的块,这些单独的块几乎肯定无法解析为合法的 JSON。 (2认同)