python ijson处理大json文件(内存溢出解决)

本文介绍了一种利用Python的ijson库来解析大型JSON文件的方法。通过逐步解析并提取所需字段的方式,有效地实现了对数据的批量处理及存储。本文重点讲解了如何设置ijson解析器、遍历JSON数据并将其格式化为可用格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

code notes for explanation

# before using , please "pip install ijson",
# details by seeing official website: https://pypi.org/project/ijson/
import ijson
    flag = 0
    with open(train_path) as file:

        parser = ijson.parse(file)
        data = []
        for prefix, event, value in parser:
            # "start_map" is the beginning of a chunk of json 
            # "end_map" is the ending of a chunk of json 
            #  via getting the beginning and end of a chunk of json to format json 
            if event == "start_map":
                sinle = {}

            if prefix == "item.id":
                sinle.update({"id": value})

            if prefix == "item.title":
                sinle.update({"title": value})

            if prefix == "item.description":
                sinle.update({"description": value})
  
            if event == "end_map":
                data.append(sinle)

            if len(data)==10:
                json.dump(data,open("data/train_10.json","w"),ensure_ascii=False)
                break

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值