如何从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
相关产品推荐
相关产品推荐

