preamble
The data has been modified to prevent leakage, so please feel free to read it!
Today, a colleague put forward a requirement, I was asked to modify a previous script, the role of the script is to obtain the zabbix monitoring system to return the json data, my task is to make it easy to read the text, how to get the data is not here to repeat, only to describe how to json data processing
First, how to convert json data into python internal data types
Show the json data returned by the interface of zabbix (the data is encoded by dumps, because the original data is str type, only one line, not easy to read)
js = (get_alert(), indent=4, ensure_ascii=False) print(js) # get_alert() method is to get json data, encode it and assign it to js, print js, the result is as follows: # indent = 4 means to set the indentation to 4 spaces. # ensure_ascii=Falseparameter is to disable theasciiencodings,If you don't prohibit the use of,Chinese characters will be output asASCIIclassifier for length or distance (yard), happenings etc
{ "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}<{$} 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" }
Next we need to decode the json object
js_loads_data = (js) # The decoded data is converted topythonNative Dictionary Types(dict)
We need to decode the data type inside the json object into the corresponding data type after the dict,
json | python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
It doesn't matter if you can't remember, there are ways to look it up now:
print(type(js_loads_data)) >>><class 'dict'>
The type() method allows you to see the data type of the decoded data js_loads_data and find that he says dictionary type, thus knowing how to access the data inside it
print(js_loads_data["id"]) >>>3 print(type(js_loads_data["id"])) >>><class 'str'>
Accessing dictionary values is done directly by changing the subscript of the quantity
Tongli, a city in Jiangsu Province, China
print(type(js_loads_data["result"]))
You can take out the results array, but this prints the entire array, so how do you take the values inside the results array?
Second, access to nested arrays in the json object
We know that after a json object is converted to a dictionary, the corresponding type of the array is list.
So we can pass
print(type(js_loads_data["result"])) >>><class 'list'>
Access the contents of a list by subscripting the list.
print(js_loads_data['result'][0]) # You can take out one of the data in the list with a subscript of 0. print(type(js_loads_data['result'][0])) >>><class 'dict'> # Printing the type reveals that the first element inside the list is of type dictionary, so again we know how to access the data inside that dictionary: for key in js_loads_data['result'][0]: print(key, ":", js_loads_data['result'][0][key]) >>>summarize >>>hosts : [{'hostid': '10358', 'name': 'FTPC01(192.168.19.5)'}] >>>items : [{'itemid': '33152', 'name': 'Memory utilization', 'description': 'Memory used percentage is calculated as (100-pavailable)'}] >>>summarize # Print the keys and values in order,Observations revealed thathostscap (a poem)itemsTwo elements or list type,If you want to take a value, you have to process it.
btw, sharing an easy way to take out all elements of a list:
result_list= [(('hosts', 'NA')) for item in js_loads_data['result']]
After such processing js_loads_data['result'] three dictionaries inside the result list has been taken out by me to assign the value to the result_list this list, now result_list is a list of nested lists and then nested dictionary type (not very well understood, pay attention to observe the above json). data), so that the next operation is more simple
for tmp in result_list: print(tmp[0].get('name')) >>>windows sever >>>linus
Processing completed
III. Summary
Get a json and don't panic.
The first encoding decoding, into python native data types step by step analysis, with print (type (element)) method to run through the type of each element, understand the structure of the entire json string to understand the access methods of each type so that we can do whatever we want with the entire json data!
to this article on Python3 in the json format data analysis and processing of the article is introduced to this, more relevant Python json format data analysis content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!