【问题标题】:JSON or Python dict / list decoding problemJSON 或 Python dict/list 解码问题
【发布时间】:2019-05-27 23:39:37
【问题描述】:

我一直在使用下面的 Python 脚本尝试从 Flightradar24 中检索和提取一些数据,它似乎以 JSON 格式提取数据,并使用json.dumps 完全打印数据,但是当我尝试使用get 选择我想要的数据(在这种情况下为状态文本)会出现以下错误:

'list' 对象没有属性 '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
},

【问题讨论】:

    标签: python json list dictionary nested


    【解决方案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
    

    因为datadicts 的列表:

    "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')
    

    【讨论】:

      【解决方案2】:

      正如@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']])
      

      【讨论】:

      • 谢谢。我会试一试的。如果它可以更容易地确定我想要的数据,那将是值得的。
      猜你喜欢
      • 2018-06-23
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      相关资源
      最近更新 更多