我试图保存从URL拉取的Json数据,但是我无法将它保存在SQLite数据库中。
Json:
{"Address":"ff00000a70d57128","Celsius":26.8125,"Fahrenheit":80.2625}
我查看了一些信息并从以下资源中获得灵感:
将json数据保存到sqlite 如何在Python中将JSON转换为SQLite - 如何正确地映射JSON键到数据库列?
import threading
import json
import urllib.request
import sqlite3
def tempRequest():
# download raw json object
url = "http://10.0.0.111:8080/getdevice?device=type28_1"
data = urllib.request.urlopen(url).read().decode()
# parse json object
obj = json.loads(data)
print(obj)
tempRequest()
conn = sqlite3.connect('test.db')
c = conn.cursor()
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS data(Celcius TEXT)")
def data_entry():
c.executemany('INSERT INTO data (Celcius) ''VALUES (:Celcius)
conn.commit()
c.close()
conn.close()
create_table()
data_entry()
当我运行这个程序时所得到的是:
TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not ellipsis
我试图更改:
obj = json.loads(data)
to
obj = json.loads(str(data))
但我认为问题出在我处理数据库方面,希望能得到一些建议。感谢!
pdb
是您的好朋友。在您想要停下来的任何地方放置import pdb; pdb.set_trace()
,然后运行脚本即可。pdb 解释器会出现,您就可以像使用 Python 解释器一样检查变量,比如data
。 - Kei Minagawa