使用Python将JSON值插入MySQL表中

2024-10-01 07:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON文件从恢复请求.get

以下是我的一些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", .....

这是我的代码:

^{pr2}$

我有个错误:

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

Tags: 文件nameidjsongetemailstatusnot
2条回答

您不需要这行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()

这是正确的解决方案:

json_obj = r.json()

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

#close the connection to the database.
mydb.commit()
cursor.close()

相关问题 更多 >