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

如何从JSON对象嵌套列表中按指定termtype值提取对应条目?

实现方案

你可以用两种方式实现需求,按需选择即可:

方法1:提前过滤原始JSON数据(推荐数据量大时使用)

提前筛掉terms列表中不需要的条目,再传入json_normalize生成DataFrame,减少无效数据处理开销:

import pandas as pd
import json

# 定义需要保留的termtype范围
target_types = {"Classification", "Materials"}

with open('file_name.txt','r', encoding = 'utf8') as f:
    data = json.loads(f.read())

# 过滤terms(根据你的data结构二选一)
# 情况1:data是包含多条记录的列表
for item in data:
    item["terms"] = [t for t in item["terms"] if t["termtype"] in target_types]
# 情况2:data是单条记录的字典
# data["terms"] = [t for t in data["terms"] if t["termtype"] in target_types]

df = pd.json_normalize(data, record_path = ['terms'],meta=['objectid','medium']) 
print(df)

方法2:生成全量DataFrame后过滤(适合数据量小的场景)

先按原有逻辑生成完整DataFrame,再按条件筛选行,写法更简单:

import pandas as pd
import json

with open('file_name.txt','r', encoding = 'utf8') as f:
    data = json.loads(f.read())

df = pd.json_normalize(data, record_path = ['terms'],meta=['objectid','medium']) 
# 筛选符合条件的行
df = df[df["termtype"].isin(["Classification", "Materials"])]
print(df)

两种方法都可以得到你期望的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:09:02