這篇文章主要為大家逐層解析Python3自定義json,內(nèi)容簡而易懂,希望大家可以學(xué)習(xí)一下,學(xué)習(xí)完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
十多年的鹽田網(wǎng)站建設(shè)經(jīng)驗,針對設(shè)計、前端、開發(fā)、售后、文案、推廣等六對一服務(wù),響應(yīng)快,48小時及時工作處理。營銷型網(wǎng)站建設(shè)的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動調(diào)整鹽田建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計,從而大程度地提升瀏覽體驗。創(chuàng)新互聯(lián)從事“鹽田網(wǎng)站設(shè)計”,“鹽田網(wǎng)站推廣”以來,每個客戶項目都認(rèn)真落實執(zhí)行。用python3對json內(nèi)容逐層進(jìn)行解析,拿中國天氣網(wǎng)的接口返回數(shù)據(jù)測試,
代碼如下:
# -*- 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"解析內(nèi)容:{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/h6map/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()