python 里面处理json

本文讲述了在Python中处理JSON数据,包括将JSON转换为CSV的过程。重点介绍了如何读取JSON(使用loads和load的区别),以及利用csv.writer将字典和列表写入CSV文件的方法。

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

今天遇到json数据的批量处理

把json转成csv

其实json文件就是key value的形式,读到python就是dict,如果外面套了[],读到python里面就变成list,读取的时候需要loads和load的区别

load是对已经读入到内存的文件的解析为python的变量

loads是从硬盘读取

我没有用到dump

 

对于写csv,只需要利用csv.writer就可以了

有很多写入的形式,这里就转换成如何把dict和list写入到csv,很简单,写了几个函数

import json
import csv
import codecs
import os


def acquire_json_file_name(dir_name):
    lst = []
    for root, dirs, files in os.walk(dir_name):
        for file in files:
            if os.path.splitext(file)[1] == '.json':
                lst.append(os.path.splitext(file)[0])
    return lst


def process_json_single(filename, resname):
    file = open(filename, encoding='UTF-8')
    json_file = json.load(file)
    file.close()
    f = codecs.open(resname, 'w', 'utf_8_sig')
    writer = csv.writer(f)
    for item in json_file:
        writer.writerow(item.values())
    f.close()


def process_all_dir(source_dir, res_dir):
    list_name = acquire_json_file_name(source_dir)
    for single_name in list_name:
        print(single_name)
        file_name = source_dir + single_name + '.json'
        res_name  = res_dir + single_name + '.csv'
        process_json_single(file_name, res_name)


def process_all_dir_dict(source_dir, res_dir):
    list_name = acquire_json_file_name(source_dir)
    for single_name in list_name:
        print(single_name)
        file_name = source_dir + single_name + '.json'
        res_name = res_dir + single_name + '.csv'
        file = open(file_name, encoding='UTF-8')
        json_file = json.load(file)
        file.close()
        f = codecs.open(res_name, 'w', 'utf_8_sig')
        writer = csv.writer(f)
        writer.writerow(json_file.values())
        if json_file['user'] != 'empty':
            writer.writerow(json_file["user"].values())
        f.close()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值