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

如何用Python将含字段与数组的JSON转为指定格式CSV字符串(云函数)

解决带嵌套数组的JSON转指定格式CSV并上传GCS的问题

需求明确

输入JSON结构(单Emp对象示例):

{
  "EmpID": "E001",
  "EmpName": "John Doe",
  "Leaves": [
    {"leave": "2024-01-10"},
    {"leave": "2024-02-15"},
    {"leave": "2024-03-20"}
  ]
}

期望输出CSV格式:

E_name,E_leaves
John Doe,2024-01-10
,2024-02-15
,2024-03-20

核心要求:

  • E_name列仅首行显示EmpName,其余行留空
  • 基于内存中的CSV字符串生成(避免本地文件操作,适配云函数环境)
  • 完成后上传至GCS Bucket

解决方案代码

以下是适配云函数场景的完整实现:

import csv
import io
from google.cloud import storage

def json_to_gcs_csv(emp_json, bucket_name, destination_blob_name):
    # 初始化CSV字符串缓冲区
    output = io.StringIO()
    writer = csv.writer(output)
    
    # 写入表头
    writer.writerow(["E_name", "E_leaves"])
    
    # 处理Leaves数组,生成数据行
    leaves = emp_json.get("Leaves", [])
    emp_name = emp_json.get("EmpName", "")
    
    for idx, leave_item in enumerate(leaves):
        leave_date = leave_item.get("leave", "")
        # 首行填充EmpName,其余行留空
        name_col = emp_name if idx == 0 else ""
        writer.writerow([name_col, leave_date])
    
    # 重置缓冲区指针到开头
    output.seek(0)
    
    # 上传至GCS Bucket
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    
    # 将CSV字符串写入blob
    blob.upload_from_file(output, content_type='text/csv')
    
    return f"CSV文件已成功上传至gs://{bucket_name}/{destination_blob_name}"

# 测试用例(云函数中可替换为实际传入的JSON数据)
if __name__ == "__main__":
    test_emp = {
        "EmpID": "E001",
        "EmpName": "John Doe",
        "Leaves": [
            {"leave": "2024-01-10"},
            {"leave": "2024-02-15"},
            {"leave": "2024-03-20"}
        ]
    }
    print(json_to_gcs_csv(test_emp, "your-bucket-name", "employee_leaves.csv"))

关键细节说明

  1. 内存中生成CSV:使用io.StringIO替代本地文件,完全在内存中构建CSV内容,适配云函数无持久化存储的环境。
  2. 列值控制:通过enumerate获取数组索引,仅在索引为0(第一行数据)时填充E_name列,其余行传入空字符串。
  3. GCS上传适配:利用google-cloud-storage库的upload_from_file方法直接将StringIO缓冲区的内容上传,无需额外文件转换。

云函数依赖配置

在云函数的部署包中需包含requirements.txt,内容如下:

google-cloud-storage>=2.15.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:33:31