用python3对json内容逐层进行解析,拿中国天气网的接口返回数据测试,代码如下:

# -*- coding: utf-8 -*-
import operator as op
from collections import defaultdict


class Json(object):

    def __init__(self, json: str):
        sth = eval(json)
        load = lambda sth: sth if op.eq(type(sth).__name__, dict.__name__) else None
        self.json_dict = load(sth)
        self.ret_j = defaultdict(dict)
        self.analyze(self.json_dict)

    def analyze(self, j_dict: dict, lvl=0) -> None:
        lvl += 1
        for k in j_dict:
            v = j_dict[k]
            v_type = type(v)
            try:
                self.ret_j[lvl][str(j_dict)].append(f"{k}:{v}")
            except:
                self.ret_j[lvl][str(j_dict)] = []
                self.ret_j[lvl][str(j_dict)].append(f"{k}:{v}")
            if op.eq(v_type.__name__, dict.__name__):
                self.analyze(v, lvl)
            elif op.eq(v_type.__name__, list.__name__):
                for each in v:
                    if op.eq(type(each).__name__, dict.__name__):
                        self.analyze(each, lvl)

    def get_analysis(self) -> None:
        print(f"这个json拢共分{len(self.ret_j)}层")
        print("------")
        for lvl in self.ret_j:
            print(f"第{lvl}层解析")
            for root in self.ret_j[lvl]:
                print(f"解析内容:{root}")
                for each in self.ret_j[lvl][root]:
                    print(each)
            print("------")


if __name__ == '__main__':
    try:
        import requests
    except:
        exit(0)
    url = "http://forecast.weather.com.cn/napi/h5map/city/101/jQuery1533133004035?callback=jQuery1533133004035"
    r = requests.get(url)
    d_r = r.content.decode()
    json_4_test = d_r[d_r.index("(") + 1:d_r.index(")")]
    Json(json_4_test).get_analysis()

其中json_4_test是待解析的json字符串。

设计思路:

Python3自定义json逐层解析器_python