我一直在使用下面的Python脚本尝试从Flightradar24检索和提取一些数据,看来它以JSON格式提取了数据,并且可以使用json.dumps
完全打印出数据,但是当我尝试使用get
选择我想要的数据(在这种情况下为状态文本),它会出现以下错误:
“列表”对象没有属性“获取”
数据是JSON还是列表?我现在很困惑。
我刚开始使用JSON格式的数据,将不胜感激!
脚本:
import flightradar24
import json
flight_id = 'BA458'
fr = flightradar24.Api()
flight = fr.get_flight(flight_id)
y = flight.get("data")
print (json.dumps(flight, indent=4))
X= (flight.get('result').get('response').get('data').get('status').get('text'))
print (X)
输出数据样本:
{
"result": {
"request": {
"callback": null,
"device": null,
"fetchBy": "flight",
"filterBy": null,
"format": "json",
"limit": 25,
"page": 1,
"pk": null,
"query": "BA458",
"timestamp": null,
"token": null
},
"response": {
"item": {
"current": 16,
"total": null,
"limit": 25
},
"page": {
"current": 1,
"total": null
},
"timestamp": 1546241512,
"data": [
{
"identification": {
"id": null,
"row": 4852575431,
"number": {
"default": "BA458",
"alternative": null
},
"callsign": null,
"codeshare": null
},
"status": {
"live": false,
"text": "Scheduled",
"icon": null,
"estimated": null,
"ambiguous": false,
"generic": {
"status": {
"text": "scheduled",
"type": "departure",
"color": "gray",
"diverted": null
},
答案 0 :(得分:1)
您可以使用print(type(variable_name))
来查看其类型。列表不支持.get(key[,default])
-dict
的列表支持。
X = (flight.get('result').get('response').get('data').get('status').get('text'))
# ^^^^^^^^ does not work, data is a list of dicts
data
是dict
的列表:
"data": [ # <<<<<< this is a list { "identification": { "id": null, "row": 4852575431, "number": { "default": "BA458", "alternative": null }, "callsign": null, "codeshare": null }, "status": {
这应该有效:
X = (flight.get('result').get('response').get('data')[0].get('status').get('text')
答案 1 :(得分:1)
@PatrickArtner指出,问题是您的data
实际上是列表而不是字典。顺便说一句,如果您要使用辅助函数在嵌套字典上反复应用dict.get
,您可能会发现代码更具可读性:
from functools import reduce
def ng(dataDict, mapList):
"""Nested Getter: Iterate nested dictionary"""
return reduce(dict.get, mapList, dataDict)
X = ng(ng(flight, ['result', 'response', 'data'])[0], ['status'[, 'text']])