我正在嘗試從飛行模擬 JSON 表中提取一些資料。它每 15 秒更新一次,我一直在嘗試拉print(obj['pilots']['flight_plans']['cid']). 但是我得到了錯誤
Traceback (most recent call last):
File "main.py", line 18, in <module>
print(obj['pilots']['flight_plans']['cid'])
TypeError: list indices must be integers or slices, not str
我的代碼如下
import json
from urllib.request import urlopen
import urllib
# initial setup
URL = "https://data.vatsim.net/v3/vatsim-data.json"
# json entries
response = urllib.request.urlopen(URL)
str_response = response.read().decode('utf-8')
obj = json.loads(str_response)
# result is connections
# print(obj["general"]["connected_clients"])
print(obj['pilots']['flight_plans']['cid'])
print(obj["general"]["connected_clients"])確實有效。
uj5u.com熱心網友回復:
調查你obj的print(json.dumps(obj,indent=2). 您會發現pilots鍵是包含flight_plan(不是復數)和cid鍵的字典串列。這是前幾行:
{
"general": {
"version": 3,
"reload": 1,
"update": "20220301062202",
"update_timestamp": "2022-03-01T06:22:02.245318Z",
"connected_clients": 292,
"unique_users": 282
},
"pilots": [
{
"cid": 1149936,
"name": "1149936",
"callsign": "URO504",
"server": "UK",
"pilot_rating": 0,
"latitude": -23.39706,
"longitude": -46.3709,
"altitude": 9061,
"groundspeed": 327,
"transponder": "0507",
"heading": 305,
"qnh_i_hg": 29.97,
"qnh_mb": 1015,
"flight_plan": {
"flight_rules": "I",
"aircraft": "A346",
...
例如,遍歷飛行員串列并列印 name/cid:
for pilot in obj['pilots']:
print(pilot['name'],pilot['cid'])
輸出:
1149936 1149936
Nick Aydin OTHH 1534423
Oguz Aydin 1429318
Marvin Steglich LSZR 1482019
Daniel Krol EPKK 1279199
... etc ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/435537.html
