user2966197 user2966197 - 6 months ago 22
JSON Question

error in accessing a nested json within a list in a json in python

I have this sample

json
data that is coming as a response from a
POST
request-
response
is the name of below sample
json
data variable:

{
"statusCode": "OK",
"data": [
{
"id": -199,
"result": {
"title": "test1",
"group": "test_grp2"
}
},
{
"id": -201,
"result": {
"title": "test2",
"group": "test_grp2"
}
}
]
}


Now what I want to do is form a
list of list
where each list will have
id
,
title
,and
group
values from above
json
data. Here is what my code looks like:

def get_list():
# code to get the response from POST request

json_data = json.loads(response.text)
group_list = []

if json_data['statusCode'] == 'OK':
for data in json_data['data']:
print(data)
for result_data in data['result']:
title = result_data['title']
group = result_data['group']
group_list.append([data['id'],title,group])

return(group_list)


When I execute this I get error as
list indices must be int not str
at line
title = result_data['title]
. How can I form the list of list above?

Answer Source

data['result'] in your case is a dictionary. When you iterate over it using for result_data in data['result'], you get the keys - in other words, result_data is a string and it does not support string indexing.

Instead, you meant:

for data in json_data['data']:
    result_data = data['result']

    title = result_data['title']
    group = result_data['group']

Or, alternatively, you can make use of a list comprehension:

group_list = [(data['id'], data['result']['title'], data['result']['group'])
              for data in json_data['data']]
print(group_list)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download