gpt4 book ai didi

python - JSON 或 Python dict/list 解码问题

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:13 24 4
gpt4 key购买 nike

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

'list' object has no attribute '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
},

最佳答案

您可以使用 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

因为 datadict 的列表:

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

关于python - JSON 或 Python dict/list 解码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53987445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com