0

I wish to loop through the following json dictionary:

hgetjsonObject = {
    u 'jsonrpc': u '2.0', u 'result': [{
        u 'hosts': [{
            u 'status': u '0',
            u 'hostid': u '10394',
            u 'name': u 'vsclap01l'
        }, {
            u 'status': u '0',
            u 'hostid': u '10395',
            u 'name': u 'vsclap03l'
        }, {
            u 'status': u '0',
            u 'hostid': u '10396',
            u 'name': u 'vscldb04l'
        }],
        u 'groupid': u '4',
        u 'name': u 'Zabbix servers'
    }], u 'id': 2
}

Here is what I have tried so far:

print(hgetjsonObject['result'][0]['hosts'][0])

But when I run it, it aborts with the following:

{u'status': u'0', u'hostid': u'10394', u'name': u'vsclap01l'}
Traceback (most recent call last):
  File "./automaton.py", line 341, in <module>
    print(hgetjsonObject['result'][0]['hosts'][0])
IndexError: list index out of range

I want to be able to do something like this:

for eachhost in hgjsonObject['result']:
    print(eachhost['hostid'],eachhost['name'])

When I run the for loop, I get errors.

2
  • print(eachhost['hosts'][0]["hostid"],eachhost['hosts'][0]["name"]) Commented Mar 23, 2019 at 19:06
  • print(hgetjsonObject['result'][0]['hosts'][0]) runs without any error. can you show us file automaton.py Commented Mar 23, 2019 at 19:17

2 Answers 2

1

I see two problems. 1) there is space between u an field in your dictionary which will cause issue.

2) because result is a list and under that hosts is another list, you should iterate through both the lists

for eachresult in hgetjsonObject['result']:
         for eachhost in eachresult['hosts']:
             print(eachhost['hostid'],eachhost['name'])

Output:

10394 vsclap01l 10395 vsclap03l 10396 vscldb04l

Sign up to request clarification or add additional context in comments.

Comments

0

for access to hosts key iterate in this way:

>>> for eachhost in hgetjsonObject['result'][0]['hosts']:
        print(eachhost["hostid"], eachhost["name"])

('10394', 'vsclap01l')
('10395', 'vsclap03l')
('10396', 'vscldb04l')

Comments

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.