1

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

You can extract the list of lists directly using a list comprehension:

>>> [[d['id'], d['result']['title'], d['result']['group']] for d in json_data['data']]
[[-199, 'test1', 'test_grp2'], [-201, 'test2', 'test_grp2']]

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.