我尝试将 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 无法再次插入它呢?