gpt4 book ai didi

python - TinyDB插入失败

转载 作者:行者123 更新时间:2023-12-01 04:15:20 24 4
gpt4 key购买 nike

我尝试将 Python 对象的 JSON 序列化插入 tinydb 。它工作一次,然后失败。

from tinydb import TinyDB, Query
import json

class Test:
def __init__(self):
self.test = "a"

def to_JSON(self):
return json.dumps(self, default=lambda o: o.__dict__)

db = TinyDB("test.json")
print(Test().to_JSON)
db.insert(Test().to_JSON())
print("Second insert")
db.insert(Test().to_JSON())

导致

{"test": "a"}
Second insert
Traceback (most recent call last):
File "test.py", line 15, in <module>
db.insert(Test().to_JSON())
File "/usr/lib/python3.4/site-packages/tinydb/database.py", line 287, in insert
data = self._read()
File "/usr/lib/python3.4/site-packages/tinydb/database.py", line 248, in _read
return self._storage.read()
File "/usr/lib/python3.4/site-packages/tinydb/database.py", line 38, in read
data[eid] = Element(val, eid)
File "/usr/lib/python3.4/site-packages/tinydb/database.py", line 20, in __init__
self.update(value)
ValueError: dictionary update sequence element #0 has length 1; 2 is required

JSON 本身对我来说看起来非常有效,那么为什么tinydb 无法再次插入它呢?

最佳答案

我之前的理解是错误的。 insert() 需要一个 dict 对象,而 json.dumps() 生成一个字符串。

from tinydb import TinyDB, Query
import json

class Test:
def __init__(self):
self.test = "a"

def to_JSON(self):
return json.loads(json.dumps(self, default=lambda o: o.__dict__))

db = TinyDB("test.json")
db.insert(Test().to_JSON())
print("Second insert")
db.insert(Test().to_JSON())

关于python - TinyDB插入失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34373857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com