json的xpath:简易数据查询

class JsonQuery(object):
    def __init__(self, data):
        super(JsonQuery, self).__init__()
        self.data = data

    def get(self, path, default=None):
        if self.data is None or path == '':
            return self.data
        query_keys = path.split("/")
        key = query_keys[0]
        left_path = '/'.join(query_keys[1:])
        if isinstance(self.data, list):
            return [JsonQuery(v).get(path, default) if v else None for v in self.data]
        else:
            return JsonQuery(dict.get(self.data, key, default)).get(left_path, default)

 

运行效果:

d = {"main":[{"x":[{"x1":1,"x2":2},{"x1":11,"x2": 12}],"y":2},{"x":[{"x1":3,"x2":4}],"y":4}]}
>>> info = JsonQuery(d)
>>> info.get('main')
[{'y': 2, 'x': [{'x2': 2, 'x1': 1}, {'x2': 12, 'x1': 11}]}, {'y': 4, 'x': [{'x2': 4, 'x1': 3}]}]
>>> info.get('main/x')
[[{'x2': 2, 'x1': 1}, {'x2': 12, 'x1': 11}], [{'x2': 4, 'x1': 3}]]
>>> info.get('main/x/x1')
[[1, 11], [3]]

 

posted @ 2018-08-31 11:00  鸪斑兔  阅读(1118)  评论(0编辑  收藏  举报