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

