ryans11 ryans11 - 6 months ago 16
JSON Question

Extracting multiple fields from json output

Hi folks im new to asking questions in stack but I want to know what is the process in order to remove the 'name' value from the json output below i know how to get the individual names through indexing

name = [groups['groups'][0]['name'] for groups in result]
but how do i get both names

from pyzabbix import ZabbixAPI

import json

z = ZabbixAPI(url='https://zabbix.server,user='xxxx',password='xxxx')
result = z.host.get(output='groupid',selectGroups='extend', filter={'host' : 'mailpphfprd01'})


name = [groups['groups'] for groups in result]

name


Json Output:

[[{u'flags': u'0',
u'groupid': u'110',
u'internal': u'0',
u'name': u'- GSOC - Systems'},
{u'flags': u'0',
u'groupid': u'313',
u'internal': u'0',
u'name': u'Applications - Email Digest'}]]


Required output

[u'- GSOC - Systems' u'Applications - Email Digest']

Answer

You should be able to do it with a list-comprehension:

json_output = [[{u'flags': u'0',
                 u'groupid': u'110',
                 u'internal': u'0',
                 u'name': u'- GSOC - Systems'},
                {u'flags': u'0',
                 u'groupid': u'313',
                 u'internal': u'0',
                 u'name': u'Applications - Email Digest'}]]

names = [d['name'] for d in json_output[0]]

print(names)  # -> [u'- GSOC - Systems', u'Applications - Email Digest']