如何从大文件中读取行分隔的JSON(逐行)

2024-06-10 22:32:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试加载一个大文件(大小为2GB),该文件由JSON字符串填充,用换行符分隔。例如:

{
    "key11": value11,
    "key12": value12,
}
{
    "key21": value21,
    "key22": value22,
}
…

我现在导入它的方式是:

content = open(file_path, "r").read() 
j_content = json.loads("[" + content.replace("}\n{", "},\n{") + "]")

这看起来像是一个技巧(在每个JSON字符串之间添加逗号,以及一个开始方括号和结束方括号,使其成为一个正确的列表)。

有没有更好的方法来指定JSON分隔符(换行符\n而不是逗号,)?

而且,Python似乎无法为从2GB数据构建的对象正确分配内存,在我逐行读取文件时,是否有方法构造每个JSON对象?谢谢!


Tags: 文件对象方法字符串jsoncontent逗号方括号
3条回答

这将适用于您提供的特定文件格式。如果格式更改,则需要更改分析行的方式。

{
    "key11": 11,
    "key12": 12
}
{
    "key21": 21,
    "key22": 22
}

只需逐行阅读,并在运行时构建JSON块:

with open(args.infile, 'r') as infile:

    # Variable for building our JSON block
    json_block = []

    for line in infile:

        # Add the line to our JSON block
        json_block.append(line)

        # Check whether we closed our JSON block
        if line.startswith('}'):

            # Do something with the JSON dictionary
            json_dict = json.loads(''.join(json_block))
            print(json_dict)

            # Start a new block
            json_block = []

如果您对解析一个非常大的JSON文件而不将所有内容保存到内存感兴趣,那么您应该查看JSON.load API中的object_hook或object_pairs_hook回调方法。

此时只需读取每一行并构造一个json对象:

with open(file_path) as f:
    for line in f:
        j_content = json.loads(line)

这样,您就可以加载正确的完整json对象(前提是json值中的某个地方或json对象的中间没有\n),并且避免了内存问题,因为每个对象都是在需要时创建的。

还有一个答案

https://stackoverflow.com/a/7795029/671543

contents = open(file_path, "r").read() 
data = [json.loads(str(item)) for item in contents.strip().split('\n')]

相关问题 更多 >