JSRB
JSRB

Reputation: 2613

How to access a API returned object in Python to grab its data

I'm struggling with kind of a trivial issue. I call an API endpoint and receive the following response as an object:

{
    'data': [{
                'id': 18136910,
                'league_id': 501,
                'season_id': 18369,
                'stage_id': 77453684,
                'round_id': 247435,
                'group_id': None,
                'aggregate_id': None,
                'venue_id': 219,
             }  
             { ....
  1. Approach: Turn object into dict and grab data
print(response.json().data)

# Prints AttributeError: 'dict' object has no attribute 'data'
  1. Approach to enter the object
print(response.data) or print(response.data[0])

# Prints AttributeError: 'Response' object has no attribute 'data'

So how to assign e.g. 'id' to a variable x?

Upvotes: 0

Views: 429

Answers (2)

Dipto Mondal
Dipto Mondal

Reputation: 764

Try like this:

You need to access dict object with key.

res = response.json()
print(res['data'])

Upvotes: 1

Leonard
Leonard

Reputation: 833

You are using the dict incorrectly. To get the id try:

print(response.json()['data'][0]['id'])

To access the value with key "x" of a dict d you should use d["x"] or d.get("x").

Upvotes: 1

Related Questions