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'

JSRB
  • 2,492
  • 1
  • 17
  • 48
  • 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')` – JacobIRR Sep 25 '19 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 – DeepSpace Sep 25 '19 at 17:25
  • related: https://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute – DeepSpace Sep 25 '19 at 17:28

1 Answers1

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.

joueswant
  • 136
  • 10
  • 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? – JSRB Sep 25 '19 at 17:52
  • 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'])` – joueswant Sep 25 '19 at 18:15