Python 向sqlite db发送嵌套json对象时出现问题
我有一个json对象的大文件,每行一个对象。我想将此数据发送到sqlite数据库。每个json对象的格式如下:Python 向sqlite db发送嵌套json对象时出现问题,python,json,sqlite,Python,Json,Sqlite,我有一个json对象的大文件,每行一个对象。我想将此数据发送到sqlite数据库。每个json对象的格式如下: {"1": {"google": 5}, "2": "", "3": 0.0, "4": [10.0, 20.0, 30.0, 20.0], "6": "", "7": 2, "8": {}, "9": 1.0, "10": 0.0} c.execute('''create table daily (1 text, 2 text,
{"1": {"google": 5},
"2": "",
"3": 0.0,
"4": [10.0, 20.0, 30.0, 20.0],
"6": "",
"7": 2,
"8": {},
"9": 1.0,
"10": 0.0}
c.execute('''create table daily
(1 text,
2 text,
3 text,
4 text,
5 text,
6 text,
7 text,
8 text,
9 text,
10 text)''')
我尝试了此代码,但出现以下错误:
query = "insert into daily values (?,?,?,?,?,?,?,?,?,?)"
columns = ['1', '2', '3', '4',
'5', '6','7',
'8', '9', '10']
with open(JSON_FILE) as f:
head = islice(f, 5)
for x in head:
line = json.loads(x)
keys = tuple(line[c] for c in columns)
c.execute(query, keys)
InterfaceError: Error binding parameter 0 - probably unsupported type.
两个问题:
1) 为什么我会犯这个错误?我假设它和first-hey的值是嵌套dict有关,但我不确定如何修复它
2) 目前,我创建了如下表:
{"1": {"google": 5},
"2": "",
"3": 0.0,
"4": [10.0, 20.0, 30.0, 20.0],
"6": "",
"7": 2,
"8": {},
"9": 1.0,
"10": 0.0}
c.execute('''create table daily
(1 text,
2 text,
3 text,
4 text,
5 text,
6 text,
7 text,
8 text,
9 text,
10 text)''')
理想情况下,我希望对象中第一个键的key:value对有单独的列。同样,我认为这是可能的,但我不太确定如何做到这一点。如果您有一个
MongoClient
连接到正在运行的服务器,只需将json
插入数据库:
client.db.collection.insert(json) # insert the json in the collection of a database db
要简单地检索条目,请使用数据库db
的给定集合的find
方法:
entries = client.db.collection.find() # find the entries without a specified argument
只要你有JSON,为什么不使用NoSQL?@MalikBrahimi这是个好问题。嗯,我以前从未使用过NoSQL,所以这可能就是原因。但是,试图将这个JSON放入sqlite数据库让我非常头疼。你会推荐mongo还是其他nosql db?是的,一定要使用Monogo!文档数据库完全取消了表和行模型,将所有相关数据以JSON、XML或其他格式存储在一个“文档”中,可以分层嵌套值。