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

Python实现API返回嵌套JSON数据转换为第一范式扁平化表格

解决方法

你可以直接用Python内置模块完成处理,不需要额外安装第三方依赖,步骤如下:

方法1:仅用标准库实现

import json

# 1. 加载JSON数据,可替换为从API获取的响应内容
raw_data = """
{
  "Customers": [
    {
      "first_name": "John",
      "last_name": "Doe",
      "middle_initial": null,
      "phone_numbers": [
        {
          "id": "1",
          "primary": false
        },
        {
          "id": "2",
          "primary": true
        }
      ]
    }
  ]
}
"""
data = json.loads(raw_data)

# 2. 扁平化处理:把每个手机号拆为单独行,保留上层客户信息
flatten_rows = []
for customer in data["Customers"]:
    base_info = {
        "first_name": customer["first_name"].lower(),
        "last_name": customer["last_name"].lower(),
        "middle_initial": str(customer["middle_initial"]).lower()
    }
    for phone in customer["phone_numbers"]:
        row = base_info.copy()
        row["phone_number_id"] = phone["id"]
        row["phone_number_primary"] = str(phone["primary"]).lower()
        flatten_rows.append(row)

# 3. 格式化输出为对齐的表格
headers = ["first_name", "last_name", "middle_initial", "phone_number_id", "phone_number_primary"]
# 计算每列宽度,设置最小间距保证对齐
col_widths = [max(len(h), max(len(row[h]) for row in flatten_rows)) + 5 for h in headers]

# 输出表头
print("".join(h.ljust(col_widths[i]) for i, h in enumerate(headers)))
# 输出每行内容
for row in flatten_rows:
    print("".join(row[h].ljust(col_widths[i]) for i, h in enumerate(headers)))

运行后输出和你要求的格式完全一致。

方法2:用pandas快速实现(适合大量数据场景)

如果已经安装pandas,也可以用内置的json_normalize方法直接完成扁平化:

import pandas as pd
import json

raw_data = """你的JSON字符串"""
data = json.loads(raw_data)

df = pd.json_normalize(
    data["Customers"],
    record_path="phone_numbers", # 指定要展开的嵌套数组
    meta=["first_name", "last_name", "middle_initial"], # 指定要保留的上层字段
    record_prefix="phone_number_" # 给展开的字段加前缀避免重名
)

# 转换为小写和预期格式后输出
df["first_name"] = df["first_name"].str.lower()
df["last_name"] = df["last_name"].str.lower()
df["middle_initial"] = df["middle_initial"].astype(str).str.lower()
df["phone_number_primary"] = df["phone_number_primary"].astype(str).str.lower()

# 按指定列顺序输出,对齐格式
print(df[["first_name", "last_name", "middle_initial", "phone_number_id", "phone_number_primary"]].to_string(index=False))

内容的提问来源于stack exchange,提问作者Chicken Sandwich No Pickles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:36:05