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

Python检查嵌套JSON中指定键值对是否存在及优化方案

嵌套JSON数组中查找符合条件元素的优化方案

问题背景

需要检查嵌套JSON的prices数组中,是否存在任意一项同时满足priceType == "04"且countriesIncluded == "DE",若存在则获取对应的priceAmount;若不存在则标记为"False"。

现有代码存在逻辑缺陷:循环会遍历所有元素,neupreis会被最后一个元素的结果覆盖——即使前面有符合条件的项,也会被后续不符合的项改成"False"。

原代码:

r = requests.get(f'https://api.vlb.de/api/v2/product/{isbn}/ean?access_token=9xx9xxxxxc9')
vlb = json.loads(r.text)
for i in vlb['prices']:
    if i['priceType'] == "04" and i["countriesIncluded"] == "DE":
        neupreis = i['priceAmount']
    else:
        neupreis = "False"

优化方案

方案1:找到符合条件项后立即终止循环

这种方法避免无效遍历,找到目标后直接跳出循环,效率更高:

import requests
import json

r = requests.get(f'https://api.vlb.de/api/v2/product/{isbn}/ean?access_token=9xx9xxxxxc9')
vlb = json.loads(r.text)
neupreis = "False"  # 先默认设为不存在
for item in vlb['prices']:
    if item.get('priceType') == "04" and item.get('countriesIncluded') == "DE":
        neupreis = item['priceAmount']
        break  # 找到符合条件的项就终止循环

用item.get()替代直接索引,可避免键不存在时抛出异常,增强代码健壮性。

方案2:使用next()函数实现简洁写法

利用Python生成器表达式结合next(),一行代码完成查找,代码更简洁:

import requests
import json

r = requests.get(f'https://api.vlb.de/api/v2/product/{isbn}/ean?access_token=9xx9xxxxxc9')
vlb = json.loads(r.text)
neupreis = next(
    (item['priceAmount'] for item in vlb['prices'] 
     if item.get('priceType') == "04" and item.get('countriesIncluded') == "DE"),
    "False"
)

next()会返回生成器中第一个符合条件元素的priceAmount,若没有符合条件的元素,则返回指定默认值"False"。

方案3:仅判断是否存在符合条件的项

如果只需要判断存在性(不需要获取priceAmount),可以用any()函数:

has_match = any(
    item.get('priceType') == "04" and item.get('countriesIncluded') == "DE"
    for item in vlb['prices']
)

has_match会返回True或False,直接表示是否存在符合条件的项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:48:22