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

如何在Python中规范化多层嵌套的复杂JSON数据

解决多层嵌套JSON转Pandas表格的问题

原始数据

data = 
{
  "id": 12345,
  "name": "Doe",
  "gender": {
    "textEn": "Masculin"
  },
  "professions": [
    {
      "job_description": {
        "textEn": "Job description"
      },
      "cetTitles": [
        {
          "cetTitleType": {
            "textEn": "Recognition"
          },
          "issuanceDate": "1992-04-14T00:00:00Z",
          "phoneNumbers": [
            "123 221 00 70"
          ]
        }
      ]
    }
  ]
}

问题描述

使用pd.json_normalize可以处理一层嵌套数据(如gender),但无法直接访问更深层级的信息。尝试用pd.json_normalize(data,record_path=['professions','job_description'],meta='id')获取职位描述时触发TypeError,需要将所有数据提取为单行多字段的表格。

解决方法

针对多层嵌套(professions和cetTitles均为数组),需要指定正确的record_path指向最内层数组,同时在meta中包含所有外层需要保留的字段,之后再调整列名和格式:

import pandas as pd

data = {
  "id": 12345,
  "name": "Doe",
  "gender": {
    "textEn": "Masculin"
  },
  "professions": [
    {
      "job_description": {
        "textEn": "Job description"
      },
      "cetTitles": [
        {
          "cetTitleType": {
            "textEn": "Recognition"
          },
          "issuanceDate": "1992-04-14T00:00:00Z",
          "phoneNumbers": [
            "123 221 00 70"
          ]
        }
      ]
    }
  ]
}

# 归一化最内层的cetTitles数组,同时携带所有外层元数据
df = pd.json_normalize(
    data,
    record_path=['professions', 'cetTitles'],
    meta=[
        'id',
        'name',
        ['gender', 'textEn'],
        ['professions', 'job_description', 'textEn']
    ]
)

# 重命名列名以匹配目标格式
df.rename(columns={
    'gender.textEn': 'gender',
    'professions.job_description.textEn': 'job_description',
    'cetTitleType.textEn': 'cetTitleType'
}, inplace=True)

# 提取phoneNumbers列表中的唯一元素
df['phoneNumbers'] = df['phoneNumbers'].str[0]

# 调整列顺序
df = df[['id', 'name', 'gender', 'job_description', 'cetTitleType', 'issuanceDate', 'phoneNumbers']]

最终输出表格

idnamegenderjob_descriptioncetTitleTypeissuanceDatephoneNumbers
12345DoeMasculinJob descriptionRecognition1992-04-14T00:00:00Z123 221 00 70

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:12:31