Python3中對json格式數(shù)據(jù)的分析處理
數(shù)據(jù)已經(jīng)過修改,以防泄密,請放心閱讀今天同事提出一個需求,要求我修改之前的某腳本,該腳本的作用是獲取zabbix監(jiān)控系統(tǒng)返回的json數(shù)據(jù),我的任務(wù)是使其變成易讀的文本,如何獲取數(shù)據(jù)不在此贅述,只描述如何對json數(shù)據(jù)進行處理
一、如何將json數(shù)據(jù)轉(zhuǎn)換成python內(nèi)部的數(shù)據(jù)類型展示一下zabbix的接口返回的json數(shù)據(jù)(數(shù)據(jù)經(jīng)過dumps編碼了,因為原數(shù)據(jù)為str類型,只有一行,不易讀)
js = json.dumps(get_alert(), indent=4, ensure_ascii=False)print(js)# get_alert()方法為獲取json數(shù)據(jù),編碼后賦給js,打印js,結(jié)果如下:# indent = 4意為設(shè)置縮進為4個空格,# ensure_ascii=False參數(shù)是禁用ascii編碼,若不禁用,中文字符會輸出為ASCII碼
{ 'jsonrpc': '2.0', 'result': [ { 'triggerid': '123456', 'expression': '{23567}>95', 'description': 'High memory utilization > 95', 'url': '', 'status': '0', 'value': '1', 'priority': '4', 'lastchange': '123456', 'comments': '', 'error': '', 'templateid': '0', 'type': '0', 'state': '0', 'flags': '0', 'recovery_mode': '0', 'recovery_expression': '', 'correlation_mode': '0', 'correlation_tag': '', 'manual_close': '0', 'opdata': '', 'hosts': [ { 'hostid': '8888', 'name': 'window_sever' } ], 'items': [ { 'itemid': '123456', 'name': 'Memory utilization', 'description': 'Memory used percentage is calculated as (100-pavailable)' } ] }, { 'triggerid': '17099', 'expression': '{20221}<{$SWAP.PFREE.MIN.WARN} and {20222}>0', 'description': 'High swap space usage ( less than 20% free)', 'url': '', 'status': '0', 'value': '1', 'priority': '2', 'lastchange': '123456789', 'comments': 'This trigger is ignored, if there is no swap configured', 'error': '', 'templateid': '16176', 'type': '0', 'state': '0', 'flags': '0', 'recovery_mode': '0', 'recovery_expression': '', 'correlation_mode': '0', 'correlation_tag': '', 'manual_close': '0', 'opdata': 'Free: {ITEM.LASTVALUE1}, total: {ITEM.LASTVALUE2}', 'hosts': [ { 'hostid': '10325', 'name': 'linus' } ], 'items': [ { 'itemid': '31681', 'name': 'Free swap space in %', 'description': '' }, { 'itemid': '123456', 'name': 'Total swap space', 'description': '' } ] } ], 'id': '3'}
接下來我們需要對json對象進行解碼
js_loads_data = json.loads(js)# 解碼后的數(shù)據(jù)轉(zhuǎn)為python原生的字典類型(dict)
我們需要之后json對象里面的數(shù)據(jù)類型解碼為dict之后與之對應(yīng)的數(shù)據(jù)類型、
json python object dict array list string str number (int) int number (real) float true True false False null None
記不住沒有關(guān)系,有方法可以現(xiàn)查:
print(type(js_loads_data))>>><class ’dict’>
通過type()方法可以查看解碼后數(shù)據(jù)js_loads_data的數(shù)據(jù)類型,發(fā)現(xiàn)他說字典類型,由此知道如何訪問它內(nèi)部的數(shù)據(jù)
print(js_loads_data['id'])>>>3print(type(js_loads_data['id']))>>><class ’str’>
訪問字典的值直接通過改變量的下標訪問即可
同理
print(type(js_loads_data['result']))
可以取出result數(shù)組,但是這樣是打印整個數(shù)組,那么如何取result數(shù)組的里面的值呢?
二、訪問json對象里嵌套的數(shù)組我們知道,json對象轉(zhuǎn)為字典后,數(shù)組對應(yīng)的類型為列表(list)
所以我們可以通
print(type(js_loads_data['result']))>>><class ’list’>
過列表的下標來訪問列表的內(nèi)容
print(js_loads_data[’result’][0])# 可以將列表下標為0的一個數(shù)據(jù)取出來print(type(js_loads_data[’result’][0]))>>><class ’dict’># 打印類型發(fā)現(xiàn),列表里面的第一個元素為字典類型,那么我們又知道了如何訪問該字典里面的數(shù)據(jù):for key in js_loads_data[’result’][0]: print(key, ':', js_loads_data[’result’][0][key])>>>略>>>hosts : [{’hostid’: ’10358’, ’name’: ’FTPC01(192.168.19.5)’}]>>>items : [{’itemid’: ’33152’, ’name’: ’Memory utilization’, ’description’: ’Memory used percentage is calculated as (100-pavailable)’}]>>>略# 依次打印鍵和值,觀察后發(fā)現(xiàn)hosts和items兩個元素還是列表類型,如要取值還要進行處理
btw,分享一個取出列表所有元素的簡便方法:
result_list= [(item.get(’hosts’, ’NA’)) for item in js_loads_data[’result’]]
這樣處理之后js_loads_data[‘result’]三個字典里面的result列表已經(jīng)被我取出來賦值給result_list這個列表了,現(xiàn)在result_list是列表嵌套列表再嵌套字典的類型(不太好理解,注意觀察上面的json數(shù)據(jù)),這樣使接下來的操作更為簡單
for tmp in result_list: print(tmp[0].get(’name’))>>>windows sever>>>linus
處理完成
三、總結(jié)拿到一個json不要慌,
先編碼解碼,轉(zhuǎn)成python原生的數(shù)據(jù)類型一步步分析,用print(type(元素))的方法捋清楚每個元素的類型,明白整個json串的結(jié)構(gòu)搞明白每個類型的訪問方法這樣我們就可以對整個json數(shù)據(jù)為所欲為了!
到此這篇關(guān)于Python3中對json格式數(shù)據(jù)的分析處理的文章就介紹到這了,更多相關(guān)Python json格式數(shù)據(jù)分析內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
