0

I would like to grab some values within a JSON object using Python and assign them to variables for further use in the html frontend.

I tried it using the w3c resource and by googling but I can't get any successful print:

import requests
import json

response = requests.get("https://www.api-football.com/demo/api/v2/teams/team/33")
team_data = response.json()

team_name = team_data.teams.name

print(team_name)

This is the JSON Object i get from the external API:

{
    "api": {
        "results": 1,
        "teams": [
            {
                "team_id": 33,
                "name": "Manchester United",
                "code": "MUN",
                "logo": "https://media.api-football.com/teams/33.png",
                "country": "England",
                "founded": 1878,
                "venue_name": "Old Trafford",
                "venue_surface": "grass",
                "venue_address": "Sir Matt Busby Way",
                "venue_city": "Manchester",
                "venue_capacity": 76212
            }
        ]
    }
}

The debug console tells me AttributeError: 'dict' object has no attribute 'teams'

3
  • You can't access dict keys like a JS object using dot notation. Use key lookups: team_data['teams'] or the safer get : team_data.get('teams') Commented Sep 25, 2019 at 17:22
  • @JacobIRR team_data.teams.name in this case would not have worked even in JS becuase team_data['teams'] is a list Commented Sep 25, 2019 at 17:25
  • related: stackoverflow.com/questions/4984647/… Commented Sep 25, 2019 at 17:28

1 Answer 1

1

JSONs (JavaScript Object Notation) are overall JavaScript objects used for storing serialized data. The python interpreter has an specific module import jsonthat allows to charge JSON files to Python dicts in the RAM of your machine.

In your situation:

with open('team_data.json', "r") as fobj:
    dataset = json.load(fobj)
    print('Teams data: ', dataset['api']['teams'])

From here you can work with it as a normal dict.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your insights. I get the JSON from an external API. Thus using your code gives me ```no such file 'team_data.json', how to avoid this?
So you are not storing the json, and there is no json file created yet, sorry I miss interepreted. Try directly print(team_data['api']['teams'])

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.