简体   繁体   English

如何从 json 响应中获取 output 特定数据?

[英]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.我对在 python 中使用 API 相当陌生,我正在尝试创建一个系统来输出以前赛车比赛的数据。 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).我已经向 API 发送了请求,但我很难将其发送到 output 一个特定的数据(例如时间、位置)。 I get this when I just print the raw JSON data sent.当我打印发送的原始 JSON 数据时,我得到了这个。

{
    "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.只是为了掌握 API,我只是试图 output 一个特定种族的简单数据,一旦我能做到这一点,我就能够扩大它和 output 各种数据。 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:我以为它就像输入print(data['time'])一样简单(如下所示),但我收到一条错误消息:

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] Races 是一个数组,在这种情况下只有一场比赛,因此您可以将其指定为["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['time']会起作用,但是你有一个嵌套的字典/列表结构,所以:

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

data["MRData"] returns another dict, which has a key "RaceTable" . data["MRData"]返回另一个字典,它有一个键"RaceTable" The value of this key is again a dictionary which has a key "Races" .这个键的值又是一个字典,它有一个键"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 .比赛再次成为关键time的命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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