0

Currently trying to write a script that pulls data from a ZabbixAPI key. I have the script working with data pulling out then being converted to a CSV file.

The issue I am facing is that after it is being converted one of the headers I have defined has multiple values inside which I need as single headers with the value attached as its own column.

e.g. How the data displys

{'hostid': '10084', 'host': 'Zabbix server', 'name': 'Zabbix server', 'status': '0', 'inventory': {'os_full': '', 'tag': '', 'location': '', 'location_lat': '', 'location_lon': ''}}

Is the code, however as the issue is saying, the value of 'Inventory' is encompassing all the data I need to be in its own columns.

How can I separate the value to properly show this?

This is the full script

import requests
import json
import pandas as pd
import csv


url = 'http://XXX/api_jsonrpc.php' 

payload = '{"jsonrpc": "2.0", "method": "host.get", "params": {"output": ["hostid","host","name","status","location","location_lat","location_lon"],"selectInventory": ["os_full","tag","location","location_lat","location_lon"]}, "auth": "XXX", "id": 1 }'
headers = {'content-type': 'application/json-rpc'}
r = requests.post(url, data=payload, headers=headers, )
hostslist = r.json()['result']

print(type(hostslist))
print(hostslist)



file = open('hostInventory.csv', 'w+', newline='')

with file:

    header = ['hostid', 'host', 'name', 'status', 'inventory']
    writer = csv.DictWriter(file, fieldnames = header)

    writer.writeheader()
    writer.writerows(hostslist)

1 Answer 1

0

Modify the dicts first, then write as before. Example:

for host in hostlist:
    host['os_full'] = host['inventory']['os_full']
    del host['inventory']

with open('hostInventory.csv', 'w+', newline=''):

    header = ['hostid', 'host', 'name', 'status', 'os_full']
    writer = csv.DictWriter(file, fieldnames = header)

    writer.writeheader()
    writer.writerows(hostslist)
Sign up to request clarification or add additional context in comments.

1 Comment

I'll just add as this worked I had to add a host = command for each data container inside the inventory - e.g for host in hostslist: host['os_full'] = host['inventory']['os_full'] host['location_lat'] = host['inventory']['location_lat'] host['location_lon'] = host['inventory']['location_lon'] host['location'] = host['inventory']['location'] del host['inventory'] Just so other people can read the above and understand but thanks for your response

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.