簡體   English   中英

處理來自網站的 json 數據並將其添加到 mysql 數據庫時出現錯誤

[英]i am getting a error when processing json data from a website and adding it to a mysql database

Hi all i am running my python file to get data form a api and putting it in to a mysql database from json, i have used the code before the onlything that changed in where the data is comming from i have chaged the id names to make確定他們是正確的

錯誤是 Traceback(最近一次調用最后一次):文件“bne.py”,第 35 行,在 response_data ['flightData'] 中的元素:TypeError:列表索引必須是整數或切片,而不是 str

這是我的代碼

import urllib.parse
import requests
import mysql.connector
import pandas as pd


mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="*****",
  database="flightdata"
)

mycursor = mydb.cursor()




url = 'https://www.bne.com.au/sites/default/files/00API-Today.json?nocache=true'


#address = 'true'
#url = main_api + urllib.parse.urlencode({address: address})

response_data = requests.get(url).json()
# empty list for holding all the data
data = []
for element in response_data['flightData']:
    origin = ['Brisbane']
    flight_id = element['id']
    airline = element['AirlineName']
    destination = element['ToFrom']
    flightNumbers = element['FlightNumber']
    scheduledTime = element['ScheduledTimeTime']
    estimatedTime = element['EstimatedTimeTime']
    scheduledDate = element['ScheduledTimeEuro']
    latestTime = element['EstimatedTimeTime']
    status = element['status']
    print (origin, flight_id, flightNumbers, airline, destination, scheduledTime, scheduledDate, latestTime, status)

    sql = "INSERT INTO flightinfo (origin, id, airline, destinations, flightNumbers, scheduledTime, estimatedTime, scheduledDate, latestTime, status) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"

    val = ('sydney', flight_id, airline, " ".join(destination), ", ".join(flightNumbers), scheduledTime, estimatedTime,
            scheduledDate, latestTime, status)
    data.append(val)


# doing a batch insert
mycursor.executemany(sql, data)

#mydb.commit()

print(mycursor.rowcount, "was inserted.")


#print(val)
#print(pd.datetime.now().date())

response_data 是一個包含您要查找的 dict(s) 的列表。 如果您通過列表 go 使用:

for element in response_data:
    airline = element['Airline']

元素應該包含你想要的字典。

嘗試這個,

for element in response_data:
   ....

代替,

for element in response_data['flightData']:
   ...

來自 json 的響應是dict list而不是dict

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM