Python3 Custom JSON Layered parser

Source: Internet
Author: User

[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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.