码迷,mamicode.com
首页 > 编程语言 > 详细

Python3自定义json逐层解析器

时间:2018-08-01 23:50:53      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:com   name   request   callback   print   roo   nap   efault   span   

[本文出自天外归云的博客园]

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

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


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逐层解析器

标签:com   name   request   callback   print   roo   nap   efault   span   

原文地址:https://www.cnblogs.com/LanTianYou/p/9404415.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!