[This article is from the Sky Cloud-owned blog Park]
The JSON content is parsed by layer by Python3, the interface of China weather NET is returned to test the data, the code is as follows:
#-*-coding:utf-8-*-Importoperator as op fromCollectionsImportdefaultdict, DequeclassJson (object):def __init__(self, json:str): Sth=eval (JSON) load=LambdaSth:sthifOp.eq (Type (STH).__name__, Dict.__name__)ElseNone self.json_dict=load (sth) Self.ret_j=defaultdict (dict) self.analyze (self.json_dict)defAnalyze (self, j_dict:dict, lvl=0)NONE:LVL+ = 1 forKinchj_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}") ifOp.eq (V_type.__name__, Dict.__name__): Self.analyze (V, LVL)elifOp.eq (V_type.__name__, list.__name__): foreachinchV:ifOp.eq (Type (each).__name__, Dict.__name__): Self.analyze (each, LVL)defGet_analysis (self)None:Print(f"this JSON fly sub {len (self.ret_j)} layer") Print("------") forLvlinchSelf.ret_j:Print(f"section {LVL} layer parsing") forRootinchSELF.RET_J[LVL]:Print(f"parsing content: {root}") foreachinchSelf.ret_j[lvl][root]:Print(each)Print("------")if __name__=='__main__': Try: ImportRequestsexcept: 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 ()
Where Json_4_test is the JSON string to parse.
Python3 Custom JSON Layered parser