Find the position in json according to the key

Scenario 1: Sometimes the structure of the key we see after formatting the json is like this, but the key cannot be found through code analysis Scenario 2: Sometimes
we cannot determine the structure of the json, we can only judge whether the key is in In this json, and return the position of the key in json

At the same time, you can also find the corresponding position according to the value


```python
import json
import jsonpath

import ast


class HandleJson():
    def __init__(self, data):
        if isinstance(data, str):
            try:
                self.data = ast.literal_eval(data)
            except:
                pass
        elif isinstance(data, dict):
            self.data = data

    def __paths(self, data, path=''):
        '''
        用于遍历json树
        :param data: 原始数据,或者key对应的value值
        :param path: key值字符串,默认值为''
        :return:
        '''
        if isinstance(data, dict):
            for k, v in data.items():
                tmp = path + "['%s']" % k
                yield (tmp, v)
                yield from self.__paths(v, tmp)

        if isinstance(data, list):
            for k, v in enumerate(data):
                tmp = path + '[%d]' % k
                yield (tmp, v)
                yield from self.__paths(v, tmp)

    def find_key_path(self, key):
        '''
        查找key路径
        :param key: 需要查找路径的key值
        :return: 包含key值路径的list
        '''
        result = []
        values = []
        for path, value in self.__paths(self.data):
            if path.endswith("['%s']" % key):
                result.append(path)
                values.append(value)
        return result, values

    def find_value_path(self, key):
        '''
        查找某个值的路径
        :param key: 需要查找的值,限制为字符串,数字,浮点数,布尔值
        :return:
        '''
        result = []
        for path, value in self.__paths(self.data):
            if isinstance(value, (str, int, bool, float)):
                if value == key:
                    result.append(path)
        return result


if __name__ == '__main__':
    hj = HandleJson(json_data)
    key, value = hj.find_key_path('video_list')
    print(1111, key, value)


Guess you like

Origin blog.csdn.net/qq_43035475/article/details/107247754