Search code examples
pythonjsonapipython-requestszabbix

Getting keys and values from zabbix API response list Python3


I have a problem with works with data from zabbix. I create a request like below:

requests = zapi.host.get({"output": ZabbixApiValues,"selectInventory":ZabbixApiValues, "filter": {"host": ["Cisco"]}}) 

ZabbixApiValues is a list of fields which I need to get from zabbix: (list is make in other function which doesn't matter right now)

['oob_ip', 'location', 'description', 'host', 'os']
<class 'list'>

then from Zabbix API I get response:

[{'hostid': '10460', 'description': 'This is testing host', 'host': 'Cisco', 'inventory': {'hostid': '10460', 'oob_ip': '', 'location': 'Tokyo', 'os': 'Linux Mint'}}]
<class 'list'>

and now I have to get all of those fields

('host': 'Cisco', 'location': 'Tokyo' etc. etc.) 

from zabbix response and create API requests to another system in XML format. I know what to do this but I can't get necessary fields from this response. I expect I get only [key]:[value] without json children exactly: 'hostid': '10460', 'description': 'This is testing host', 'host': 'Cisco','hostid': '10460', 'oob_ip': '', 'location': 'Tokyo', 'os': 'Linux Mint' maybe as dictionary. without "inventory". Then I could get keys and values and create xml.

Now I can get string with all of data or x['inventory'] with only inventory data instead of all of fields.

Please help


Solution

  • Zabbix response is of type list and then you are converting it to json data so now it's json string you can't access elements like that, you need to load the json data like

    JSrequests = json.dumps(requests)
    x = json.loads(JSrequests)
    resp_dict = x[0]
    

    now this is a dict, you can access elements like

    x[0]['description']
    

    not sure why you are doing this, requests is of type list, no need to convert to json, get the dict out of list and access elements i.e

    x = requests[0] # dict