如何在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']]
最终输出表格
| id | name | gender | job_description | cetTitleType | issuanceDate | phoneNumbers |
|---|---|---|---|---|---|---|
| 12345 | Doe | Masculin | Job description | Recognition | 1992-04-14T00:00:00Z | 123 221 00 70 |
内容的提问来源于stack exchange,提问作者cyancyan
相关产品推荐
相关产品推荐

