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 @ 2021-07-30 14:30  猪猪猪猪侠  阅读(79)  评论(0编辑  收藏  举报