使用python将json值插入mysql表

yeotifhr  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(515)

我有一个json文件从requests.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", .....

这是我的密码:

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'
1tu0hz3e

1tu0hz3e1#

你不需要这条线 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()
uubf1zoe

uubf1zoe2#

这是正确的解决方案:

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

相关问题