{ "name":"AAA" , "age":"17" }, { "name":"BBB" , "age":"18" }, { "name":"CCC" , "age":"19" }

需要转为以下格式,以便进行数据处理:

name  age
AAA  17
BBB  18
CCC  19

json文件转csv完整代码:

import csv
import simplejson as json
# 定义转换函数
def trans(json_path, csv_path):
    json_file = open(json_path, 'r', encoding='utf8') 
    csv_file = open(csv_path, 'a', newline='', encoding='utf8')
    writer = csv.writer(csv_file)
    # 读取json数据
    dic_data = json.load(json_file)
    keys = []
    for dic in dic_data:
        keys = dic.keys()
        # 写入列名
        writer.writerow(keys)
        break
    for dic in dic_data:
        for key in keys:
            if key not in dic:
                dic[key] = ''
        writer.writerow(dic.values())
    json_file.close()
    csv_file.close()
# 调用转换函数
json_path = 'E:/abc.json'
csv_path = 'E:/abc.csv'
trans(json_path, csv_path)

注:当数据里有中文时,可能会遇到输出乱码的情况,把编码方式 utf8 改为 utf-8-sig 即可解决。

https://mp.weixin.qq.com/s/SSgeHlxr9m4T4kqKuBwgyw