如何在Python中基于多层多条件查询JSON对象?
多层级JSON数据的多条件查询方案(Python)
步骤说明
我们需要遍历JSON中的results列表,同时满足两个条件:
- 外层对象的
type值为header1 - 该对象下
header1.rich_text数组中存在type为simpletxt的子项
代码实现
首先将原始JSON转为Python字典(如果是从文件读取,可使用json.load()方法):
# 原始JSON对应的Python字典 data = { "obj": "typed", "results": [ {"obj": "blocktext","type": "header1","header1": {"rich_text": [{"type": "simpletxt","txt": "About me"}]}}, {"obj": "blocktext","type": "header1","header1": {"rich_text": [{"type": "simpletxt","txt": "Imprint"}]}}, {"obj": "blocktext","type": "header1","header1": {"rich_text": [{"type": "simpletxt","txt": "About me"}]}}, {"obj": "blocktext","type": "code","code": {"rich_text": [{"type": "javascript","txt": "ABCDEFG"}]}} ] }
方案1:获取符合条件的完整区块对象
遍历所有区块,筛选同时满足两个条件的对象,返回可遍历的列表:
matching_blocks = [] for block in data["results"]: # 检查外层type是否为header1 if block.get("type") == "header1": # 获取rich_text列表,避免键不存在时抛出异常 rich_text_items = block.get("header1", {}).get("rich_text", []) # 检查是否存在type为simpletxt的子项 has_simpletxt = any(item.get("type") == "simpletxt" for item in rich_text_items) if has_simpletxt: matching_blocks.append(block) # 遍历结果示例 for block in matching_blocks: print(block["header1"]["rich_text"][0]["txt"])
方案2:直接提取符合条件的文本内容
如果只需要txt字段的值,可以直接提取:
matching_texts = [] for block in data["results"]: if block.get("type") == "header1": for item in block.get("header1", {}).get("rich_text", []): if item.get("type") == "simpletxt": matching_texts.append(item["txt"]) # 输出结果:['About me', 'Imprint', 'About me'] print(matching_texts)
关键细节
- 使用
dict.get(key, default)方法替代直接索引(如block["type"]),可以避免因键缺失导致的KeyError,让代码更健壮。 any()函数用于快速判断数组中是否存在符合条件的元素,无需遍历整个数组。
内容的提问来源于stack exchange,提问作者STORM
相关产品推荐
相关产品推荐

