您好,登錄后才能下訂單哦!
如何在Python3中對(duì)json格式數(shù)據(jù)進(jìn)行分析處理?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
展示一下zabbix的接口返回的json數(shù)據(jù)(數(shù)據(jù)經(jīng)過dumps編碼了,因?yàn)樵瓟?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è)置縮進(jìn)為4個(gè)空格, # ensure_ascii=False參數(shù)是禁用ascii編碼,若不禁用,中文字符會(huì)輸出為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" }
接下來我們需要對(duì)json對(duì)象進(jìn)行解碼
js_loads_data = json.loads(js) # 解碼后的數(shù)據(jù)轉(zhuǎn)為python原生的字典類型(dict)
我們需要之后json對(duì)象里面的數(shù)據(jù)類型解碼為dict之后與之對(duì)應(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"]) >>>3 print(type(js_loads_data["id"])) >>><class 'str'>
訪問字典的值直接通過改變量的下標(biāo)訪問即可
同理
print(type(js_loads_data["result"]))
可以取出result數(shù)組,但是這樣是打印整個(gè)數(shù)組,那么如何取result數(shù)組的里面的值呢?
我們知道,json對(duì)象轉(zhuǎn)為字典后,數(shù)組對(duì)應(yīng)的類型為列表(list)
所以我們可以通
print(type(js_loads_data["result"])) >>><class 'list'>
過列表的下標(biāo)來訪問列表的內(nèi)容
print(js_loads_data['result'][0]) # 可以將列表下標(biāo)為0的一個(gè)數(shù)據(jù)取出來 print(type(js_loads_data['result'][0])) >>><class 'dict'> # 打印類型發(fā)現(xiàn),列表里面的第一個(gè)元素為字典類型,那么我們又知道了如何訪問該字典里面的數(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兩個(gè)元素還是列表類型,如要取值還要進(jìn)行處理
btw,分享一個(gè)取出列表所有元素的簡便方法:
result_list= [(item.get('hosts', 'NA')) for item in js_loads_data['result']]
這樣處理之后js_loads_data[‘result']三個(gè)字典里面的result列表已經(jīng)被我取出來賦值給result_list這個(gè)列表了,現(xiàn)在result_list是列表嵌套列表再嵌套字典的類型(不太好理解,注意觀察上面的json數(shù)據(jù)),這樣使接下來的操作更為簡單
for tmp in result_list: print(tmp[0].get('name')) >>>windows sever >>>linus
看完上述內(nèi)容,你們掌握如何在Python3中對(duì)json格式數(shù)據(jù)進(jìn)行分析處理的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。