在这段代码中,我想从https://thingspeak.com/channels/1441388/feed.json的字段1和字段2,并使用python3上传到我的本地数据库中;第一个";变量;TypeError:字符串索引必须是整数;。
import urllib.request
import json
import mysql.connector
url = "https://thingspeak.com/channels/1441388/feed.json"
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",database="path")
with urllib.request.urlopen(url) as url:
s=url.read()
data = json.dumps(s.decode("utf-8"))
N=10
for num in reversed(range(N + 1)) : # fetch last ten data
first = (data['feeds'][num]['field1']) # fetch field1 data from JSON
print("first",first)
second = data['feeds'][num]['field2']
print("second",second)
cursor = mydb.cursor()
insert_stmt = ("INSERT INTO details(Distance,water_level,Connected_device)"
"VALUES (%s, %s, %s)")
data = (first,second,'Arduino & GPRS')
try:
cursor.execute(insert_stmt, data)
mydb.commit()
#cursor.close()
print(cursor.rowcount, "record inserted.")
except:
mydb.rollback()
**我得到这个输出
**
**Traceback (most recent call last):
File "D:IOTBlind Stickfetch.py", line 14, in <module>
first = list(data['feeds'][num]['field1'])
TypeError: string indices must be integers**
所以我想知道我在这里做错了什么?
使用json.loads
而不是.dumps
。