使用pandas的json_normalize时多record_path键无法正常工作
处理包含多列表的JSON数据规范化问题
原始JSON数据
[ { "org_id": 1, "org_name": "Test", "super_admin": [], "sub_admin": [] }, { "org_id": 2, "org_name": "QA", "super_admin": [ { "id": 1, "first_name": "User", "last_name": null, "email": "qw@qw.com", "phone": null }, { "id": 2, "first_name": "Test", "last_name": "User", "email": "asd@qw.com", "phone": null } ], "sub_admin": [ { "id": 3, "first_name": "pd", "last_name": null, "email": "rt@rt,com", "phone": null } ] }, { "org_id": 3, "org_name": "My test Org", "super_admin": [], "sub_admin": [] }, { "org_id": 4, "org_name": "test Org", "super_admin": [], "sub_admin": [] } ]
问题重现
尝试用pd.json_normalize同时解析super_admin和sub_admin两个列表时:
df = pd.json_normalize(arr, meta=['org_name', 'org_id'], record_path=['super_admin', 'sub_admin'], errors='ignore')
抛出错误:
KeyError: "Key 'sub_admin' not found. If specifying a record_path, all elements of data should have the path."
单独解析单个列表(如仅super_admin)则正常:
pd.json_normalize(arr, meta=['org_name', 'org_id'], record_path=['super_admin'], errors='ignore')
解决方案
pd.json_normalize的record_path参数仅支持指定单个层级的路径,无法同时解析多个同级列表。要保留管理员类型的区分,需分别解析两个列表,添加类型标识后合并:
import pandas as pd # 解析super_admin并添加类型标识列 df_super = pd.json_normalize( arr, meta=['org_name', 'org_id'], record_path=['super_admin'], errors='ignore' ) df_super['admin_type'] = 'super_admin' # 解析sub_admin并添加类型标识列 df_sub = pd.json_normalize( arr, meta=['org_name', 'org_id'], record_path=['sub_admin'], errors='ignore' ) df_sub['admin_type'] = 'sub_admin' # 合并两个结果DataFrame final_df = pd.concat([df_super, df_sub], ignore_index=True)
执行后,final_df会包含所有管理员信息,通过admin_type列可清晰区分超级管理员和子管理员,同时保留org_id、org_name与管理员的关联关系。
内容的提问来源于stack exchange,提问作者user5594493
相关产品推荐
相关产品推荐

