Я пытаюсь вставить значения JSON в таблицу MySQL
У меня есть файл JSON:
[{"order":{"id":"B4589B26","status_order_id":5,"status_order_name":"Sent","customer_id":326
"order_products":[{"order_product {"id":96218,"order_id":96538,"product_id":59320,}}],"customer_email":"[email protected]","customer_company":"SARL","customer_name":"user user", .....
и вот мой код Python:
token = "xxxx"
r = requests.get('url', auth=('[email protected]', token))
mydb = pymysql.connect(host='localhost',
user='root',
passwd='user',
db='ytm_db')
cursor = mydb.cursor()
json_obj = r.json()
for ord in json_obj["order"]:
print("id:", ord["id"])
print("status_id:", ord["status_order_id"])
print('---')
cursor.execute("INSERT INTO table_test (id, status_order_id, customer_id) VALUES (%s,%s,%s)", (ord["id"], ord["status_order_id"], ord["customer_id"]))
#close the connection to the database.
mydb.commit()
cursor.close()
print ("Done")
но я получаю эту ошибку:
для ord in json_obj ["order"]: TypeError: индексы списка должны быть целыми или кусочками, а не str
Ваш объект JSON - это список заказов, поэтому вы не можете рассматривать его как dict, обратившись к его "order"
.
Вместо этого вы должны прокручивать список заказов, а затем обращаться к заказу как к dict:
for ord in json_obj:
print("id:", ord["order"]["id"])
print("status_id:", ord["order"]["status_order_id"])
print('---')
cursor.execute("INSERT INTO table_test (id, status_order_id, customer_id) VALUES (%s,%s,%s)", (ord["order"]["id"], ord["order"]["status_order_id"], ord["order"]["customer_id"]))