【发布时间】:2022-02-26 06:36:31
【问题描述】:
我尝试使用 python 将 json API 中的数据添加到 MySql 数据库中,但出现错误: xx=validate_string(i.get(x, None))AttributeError: 'str' object has no attribute 'get'
我的代码:
import requests
import json
import pymysql
headers = {
'Accept': 'application/json',
'api-key': 'xxxxx'
}
r = requests.get('https://api.example.com', params={
'Id': '432',
'Id2': '6'
}, headers = headers)
package_json=r.json()
con = pymysql.connect(host='domain.net', user='user', passwd='pass', db='test')
cursor = con.cursor()
def validate_string(val):
if val != None:
if type(val) is int:
return str(val).encode('utf-8')
else:
return val
for i in package_json:
# start off your query string
query = 'Insert into xxxx ('
t1=[]
first_item = True
for x in i:
xx=validate_string(i.get(x, None))
# append the value to the value list
t1.append(xx)
if not first_item:
# add a comma and space to the query if it's not the first item
query += ', '
# add the field name to the query
query += x
# mark that it's no longer the first item
first_item = False
# finish off the query string
query += ') VALUES {}'
# and send the query
cursor.execute(query.format(tuple(t1)))
con.commit()
con.close()
有什么想法可以解决吗?
【问题讨论】:
-
for i in package_json为您提供package_json的键列表。您是否想使用for key, i in package_json.items()?或for i in package_json.values()? -
我只是想从API中抓取东西并将它们放入Mysql数据库
标签: python mysql-python