【问题标题】:insert JSON values into a MySQL table using python使用 python 将 JSON 值插入 MySQL 表
【发布时间】:2019-01-08 22:47:03
【问题描述】:

我有一个从 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'

【问题讨论】:

    标签: python mysql json python-requests


    【解决方案1】:

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

    【讨论】:

    • 我尝试使用此代码,但出现此错误:** for ord in json_obj["order"]: TypeError: list indices must be integers or slices, not str** @Rakesh you have an请出主意?
    • 看起来json_obj 是一个列表尝试先迭代它
    • 我是python的初学者,没看懂,请你解释一下怎么做或者找什么!
    【解决方案2】:

    这是正确的解决方案:

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

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 2011-05-14
      • 2015-05-10
      • 2011-11-01
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 2019-04-08
      相关资源
      最近更新 更多