gpt4 book ai didi

python - 使用 python 将 JSON 值插入到 MySQL 表中

转载 作者:行者123 更新时间:2023-11-30 21:40:58 25 4
gpt4 key购买 nike

我有一个从 requests.get 恢复的 JSON 文件

这是我的一些 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":"user@gmail.com","customer_company":"SARL","customer_name":"user user", .....

这是我的代码:

token = "xxxx"

r = requests.get('url', auth=('user@gmail.com', token))

mydb = pymysql.connect(host='localhost',
user='root',
passwd='user',
db='ytm_db')

cursor = mydb.cursor()

data = r.json()
json_obj = json.loads(r)

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

我有这个错误:

    'not {!r}'.format(s.__class__.__name__))
TypeError: the JSON object must be str, bytes or bytearray, not 'Response'

最佳答案

你不需要这一行 json_obj = json.loads(r)r.json() 返回一个 json 响应。

例如:

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()

关于python - 使用 python 将 JSON 值插入到 MySQL 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51632003/

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