You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从GitHub仓库的JSON数据生成CSV文件?

从PhonePe Pulse仓库的JSON文件生成CSV文件的清晰步骤

前置操作

  • 克隆目标仓库到本地:git clone https://github.com/PhonePe/pulse.git
  • 若想复用已有实现,同步参考项目:git clone https://github.com/kracekumar/pulse-plus.git

分步处理(两种方式)

方式一:直接复用pulse-plus的脚本

  1. 进入pulse-plus项目目录,安装依赖:pip install -r requirements.txt
  2. 找到脚本中指定pulse仓库数据路径的配置项,修改为你本地pulse/data的绝对路径
  3. 执行项目中的主处理脚本(比如main.py,具体看项目文件结构),脚本会自动遍历所有JSON文件并生成对应的CSV文件

方式二:手动编写脚本实现

如果需要自定义处理逻辑,按以下步骤操作:

  1. 遍历JSON文件目录:定位pulse仓库中存放JSON的目录(如pulse/data/transactions、pulse/data/users),用Python的os.walk递归遍历所有.json文件
  2. 解析JSON并提取核心字段:不同类型的JSON(交易/用户数据)结构不同,需针对性提取字段。以交易数据为例,参考代码片段:
import json
import os
import csv

def extract_transaction_records(json_data):
    records = []
    # 适配pulse仓库交易JSON的层级结构
    base_info = {
        'year': json_data['data']['year'],
        'quarter': json_data['data']['quarter']
    }
    for state_item in json_data['data']['transactionData']['states']:
        record = base_info.copy()
        record.update({
            'state': state_item['state'],
            'transaction_count': state_item['metric']['count'],
            'transaction_amount': state_item['metric']['amount']
        })
        records.append(record)
    return records

def load_all_transaction_data(root_dir):
    all_records = []
    for root, _, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.json'):
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    json_obj = json.load(f)
                    all_records.extend(extract_transaction_records(json_obj))
    return all_records
  1. 写入CSV文件:用csv.DictWriter将结构化数据写入CSV,确保表头和字段对应:
def write_csv(records, output_file):
    if not records:
        print("无数据可写入")
        return
    fieldnames = records[0].keys()
    with open(output_file, 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(records)

# 执行流程示例
transaction_data = load_all_transaction_data('pulse/data/transactions')
write_csv(transaction_data, 'phonepe_transactions.csv')

关键注意事项

  • 不同维度的JSON(全国/各邦/区县、用户/交易)结构差异明显,需根据实际JSON结构调整字段提取逻辑
  • 处理大体积JSON文件时,建议分批次读取和写入,避免内存占用过高
  • 若遇到编码错误,读取或写入文件时指定encoding='utf-8'参数

内容的提问来源于stack exchange,提问作者Aditya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:05:35