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

如何在Python中使用jsonpath-ng判断指定JSON路径的键是否存在

jsonpath-ng 判断指定JSON路径是否存在的实现方法

依赖安装

首先安装jsonpath-ng库:
pip install jsonpath-ng

实现逻辑

jsonpath-ng 提供的find()方法会返回所有匹配指定JSON路径的结果集合,没有匹配项时返回空列表,因此只需判断返回列表的长度是否大于0,即可确认对应路径是否存在,效果和你需要的doesexist()方法完全一致。

完整示例代码

from jsonpath_ng import parse

# 示例JSON结构
client_json = {
    "data": [
        {
            "attributes": {
                "creators": [
                    {
                        "name": "This is a person",
                        "nameType": "Personal",
                        "givenName": "the",
                        "familyName": "person"
                    },
                    {
                        "name": "This is an organization",
                        "nameType": "Organizational",
                        "givenName": "the",
                        "familyName": "organization"
                    }
                ]
            }
        }
    ]
}

# 封装为通用的路径存在判断方法
def doesexist(json_obj, json_path: str) -> bool:
    return len(parse(json_path).find(json_obj)) > 0

# 测试用例
# 测试存在的路径
print(doesexist(client_json, "$.data[0].attributes.creators[0].name"))  # 输出:True
# 测试不存在的路径
print(doesexist(client_json, "$.data[0].attributes.creators[0].age"))  # 输出:False

注意事项

  • 请根据你的实际JSON结构调整JSON路径表达式,示例中因为最外层是data数组,所以路径前缀为$.data[0],如果你原路径$.[0].attributes.creators[0].name是省略了顶层键的写法,对应修改parse里的路径参数即可。
  • 该方法仅判断路径是否存在,不会校验路径对应值的内容、类型,符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:36:04