如何用Pandas解析嵌套JSON并提取amount、items字段数据
解决嵌套JSON数据的字段提取问题
先明确数据格式前提
你的datasetjson必须是字典组成的列表(每条数据是一个dict,整体是list)。如果是单个字典,要先包裹成列表:datasetjson = [single_data_dict],否则pd.json_normalize会只返回空索引。
方法一:用pd.json_normalize直接展开嵌套(推荐)
针对你需要提取的amount子字段和items中的指定字段,直接通过record_path展开数组,meta保留其他嵌套字段:
import pandas as pd # 示例数据集结构 datasetjson = [ { "order_id": "OD001", "amount": {"total": 200, "subtotal": 180, "tax": 20}, "items": [ {"_id": "ITEM001", "earning": 50, "variants": {"color": "red", "size": "M"}, "other": "无关字段"}, {"_id": "ITEM002", "earning": 130, "variants": {"color": "blue", "size": "L"}, "other": "无关字段"} ] }, # 更多数据... ] # 展开items数组,同时保留订单级的amount子字段和其他顶级字段 df = pd.json_normalize( datasetjson, record_path="items", # 指定要展开的数组字段 meta=[ "order_id", # 顶级字段 ["amount", "total"], # amount下的子字段,用路径写法 ["amount", "subtotal"], ["amount", "tax"] ], record_prefix="item_" # 给items里的字段加前缀,避免冲突 ) # 提取你需要的字段 final_df = df[["order_id", "amount.total", "amount.subtotal", "amount.tax", "item__id", "item_earning", "item_variants"]] # 如果variants是嵌套字典,需要进一步展开的话: final_df = pd.json_normalize( final_df.to_dict("records"), meta=["order_id", "amount.total", "amount.subtotal", "amount.tax", "item__id", "item_earning"], record_path="item_variants", record_prefix="variant_" )
方法二:用pd.DataFrame结合explode+apply提取
如果觉得json_normalize参数复杂,也可以先转成DataFrame,再分步处理:
import pandas as pd # 先转成DataFrame,此时amount和items是字典/列表类型列 df = pd.DataFrame(datasetjson) # 提取amount下的各个子字段 df["amount_total"] = df["amount"].apply(lambda x: x["total"]) df["amount_subtotal"] = df["amount"].apply(lambda x: x["subtotal"]) df["amount_tax"] = df["amount"].apply(lambda x: x["tax"]) # 展开items数组为单独行 df_exploded = df.explode("items", ignore_index=True) # 提取items里的指定字段 df_exploded["item_id"] = df_exploded["items"].apply(lambda x: x["_id"]) df_exploded["item_earning"] = df_exploded["items"].apply(lambda x: x["earning"]) df_exploded["item_variants"] = df_exploded["items"].apply(lambda x: x["variants"]) # 清理不需要的原始列 final_df = df_exploded.drop(["amount", "items"], axis=1)
关键注意点
- 如果
pd.json_normalize只显示索引,大概率是输入的datasetjson不是列表格式(比如是单个字典或空结构),先检查数据结构。 - 对于多层嵌套的字段,
json_normalize支持用["父字段", "子字段"]的路径写法指定提取。 - 如果
variants里还有多层嵌套,重复用json_normalize即可继续展开。
内容的提问来源于stack exchange,提问作者TotalNoobb
相关产品推荐
相关产品推荐

