【问题标题】:JSON / MySQL : list indices must be integers or slices, not strJSON / MySQL:列表索引必须是整数或切片,而不是 str
【发布时间】:2019-01-09 22:52:54
【问题描述】:

我正在尝试将 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":"user@gmail.com","customer_company":"SARL","customer_name":"user user", .....

这是我的 Python 代码:

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

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

但我收到此错误:

for ord in json_obj["order"]: TypeError: list indices must be integers 或切片,而不是 str

【问题讨论】:

    标签: mysql json python-3.x api


    【解决方案1】:

    您的 JSON 对象是一个订单列表,因此您不能通过访问其 "order" 键将其视为字典。

    相反,您应该遍历订单列表,然后将订单作为字典访问:

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

    【讨论】:

      猜你喜欢
      • 2016-05-25
      • 2017-11-19
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2015-12-09
      • 2021-09-01
      相关资源
      最近更新 更多