简体   繁体   中英

How do I output specific data from a json response?

I am fairly new to using APIs in python and I am trying to create a system that outputs data from previous motorsport races. I have sent requests to an API, but I am struggling to get it to just output one specific piece of data (eg. time, location). I get this when I just print the raw JSON data sent.

{
    "MRData": {
        "RaceTable": {
            "Races": [
                {
                    "Circuit": {
                        "Location": {
                            "country": "Spain",
                            "lat": "41.57",
                            "locality": "Montmeló",
                            "long": "2.26111"
                        },
                        "circuitId": "catalunya",
                        "circuitName": "Circuit de Barcelona-Catalunya",
                        "url": "http://en.wikipedia.org/wiki/Circuit_de_Barcelona-Catalunya"
                    },
                    "date": "2020-08-16",
                    "raceName": "Spanish Grand Prix",
                    "round": "6",
                    "season": "2020",
                    "time": "13:10:00Z",
                    "url": "https://en.wikipedia.org/wiki/2020_Spanish_Grand_Prix"
                }
            ],
            "round": "6",
            "season": "2020"
        },
        "limit": "30",
        "offset": "0",
        "series": "f1",
        "total": "1",
        "url": "http://ergast.com/api/f1/2020/6.json",
        "xmlns": "http://ergast.com/mrd/1.4"
    }
}

Just to get to grips with APIs I am simply trying to output a simple piece of data of a specific race, and once I can do that, I'll be able to scale it up and output all sorts of data. I'd assumed it would just be as simple as typing print(data['time']) (as seen below) but I get an error message saying this:

KeyError: 'time'

My source code:

import requests

response = requests.get("http://ergast.com/api/f1/2020/6.json")

data = response.json()


print (data["time"])

Any help is appreciated!

Like this...

import json


data = """{
   "MRData":{
      "xmlns":"http://ergast.com/mrd/1.4",
      "series":"f1",
      "url":"http://ergast.com/api/f1/2020/6.json",
      "limit":"30",
      "offset":"0",
      "total":"1",
      "RaceTable":{
         "season":"2020",
         "round":"6",
         "Races":[
            {
               "season":"2020",
               "round":"6",
               "url":"https://en.wikipedia.org/wiki/2020_Spanish_Grand_Prix",
               "raceName":"Spanish Grand Prix",
               "Circuit":{
                  "circuitId":"catalunya",
                  "url":"http://en.wikipedia.org/wiki/Circuit_de_Barcelona-Catalunya",
                  "circuitName":"Circuit de Barcelona-Catalunya",
                  "Location":{
                     "lat":"41.57",
                     "long":"2.26111",
                     "locality":"Montmeló",
                     "country":"Spain"
                  }
               },
               "date":"2020-08-16",
               "time":"13:10:00Z"
            }
         ]
      }
   }
}"""

jsonData = json.loads(data)

Races is an array, in this case there is only one race so you would desigate it as ["Races"][0]

print(jsonData["MRData"]["RaceTable"]["Races"][0]["time"])

data['time'] would work if you had a flat dictionary, but you have a nested dicts/list structure, so:

data["MRData"]["RaceTable"]["Races"][0]["time"]

data["MRData"] returns another dict, which has a key "RaceTable" . The value of this key is again a dictionary which has a key "Races" . The value of this is a list of races, of which you only have one. The races are again dicts which have the key time .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM