python一次定位键值对

1、下载jsonpath_ng

2、写一个类

from jsonpath_ng import parse

class JsonHelper:
    def __init__(self, buffer: dict):
        self._buffer = buffer

    def get(self, field: str):
        if not field.startswith('$..'):
            condition = '$..' + field
        else:
            condition = field
        ret = []
        for match in parse(condition).find(self.__dict__['_buffer']):
            ret.append(match.value)

        if not ret:
            raise Exception("field:{} is not exist".format(field))
        else:
            return ret[0]

    def set(self, field: str, value):
        if not field.startswith('$..'):
            condition = '$..' + field
        else:
            condition = field

        parse(condition).update(self.__dict__['_buffer'], value)

3、传入构造函数的参数,并调用get方法

#x表示获取到的键值对中的值
x = JsonHelper(json数据).get("键")
print(x)

4、缺点

只能获取一个键值对,如果有很多同名的键,将会只能获取到其中的一个,而且是最上面的那一个。

5、举例

image
-获取这个
image

  • 代码
content = 上面的json数据
sha1 = JsonHelper(content).get("revision")
print(sha1)
  • 结果
{'SHA1': '24e1d2bebb892f9f0d6c04b9f585fc828370d997', 'branch': [{'SHA1': '24e1d2bebb892f9f0d6c04b9f585fc828370d997', 'name': 'branch-3.5'}]}

Process finished with exit code 0

posted @   猪猪猪猪侠  阅读(84)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示