Reputation: 145
i'm trying to iterate in a json api respons and i'm unable to reach the data i need
here is a api response example. "i know it 's not complete or valid json :)"
{
"status": "running",
"reasons": [],
"nodes": {
"Server1": {
"status": "running",
and i'm using a simple for loop to iterate throught it !
for platforms in sbNode:
request = urllib2.Request(API URL)
json_res = json.load(urllib2.urlopen(request))
for node in json_res['nodes']:
print node['status']
and i'm getting an error message
TypeError: string indices must be integers
and normaly i just print the for loop to see the json data but it just print Server1.
I'm lost here ....
Help !!!
Thanks
Upvotes: 0
Views: 8134
Reputation: 8559
You are missing a level of deepness of your data since json_res['nodes']
is a dictionary
json_res['nodes'] = {
"Server1": {
"status": "running",
...
You can add a nested loop to print servers status:
for node in json_res['nodes']:
for server in node:
print server['status']
Upvotes: 0
Reputation: 5983
json_res['nodes']
is a dictionary. Iterating over a dictionary just gives you the keys, so the first value of node
could be, for example, 'Server1'
. If you want both the keys and values you can iterate using .items()
:
for key, node in json_res['nodes'].items():
If you only want the values of the nodes, you can use .values()
:
for node in json_res['nodes'].values():
Upvotes: 2