0

I'm seeking to pull specific data from a JSONs captured by an API pull. There's no problem in getting the entire JSON, but I'm experiencing problems trying to pull specific data from the JSON.

The JSON is a series of 20 data entries structured like this:

[
  {
    "id": 1,
    "body": "string",
    "grade": "100",
    "user_id": 5531,
  },

]

Here's my attempt to pull data:

import requests
import json

url = API url
headers = {'Authorization' : 'Bearer API key'}
r = requests.get(url, headers=headers)
json_data = r.json()
print(json_data["user_id"])

Which generates the following error:

TypeError: list indices must be integers or slices, not str

Clearly I'm missing something - any thoughts? All assistance greatly appreciated.

2 Answers2

1

Ok, so this should work for you:

user_id_list = []
for data in json_data:
    user_id_list.append(data['user_id'])
print(user_id_list)

You can even return the user_id_list in the last line if it is in a function, as required.

Ankit Gupta
  • 175
  • 6
1

You want to be using a python dictionary not a list. Use json.loads(). This answer here: How to extract a single value from JSON response? should help.

Braden Yonano
  • 161
  • 2
  • 12