【发布时间】:2016-09-06 04:33:15
【问题描述】:
所以我正在尝试创建一个行为类似于 dict 的类,但每当对 dict 进行更改时,它也会将自身复制到 .json 文件中。我大部分时间都在工作。但是我遇到麻烦的地方是当我将某些内容附加到字典内的列表时;它更新 dict 但不更新与 dict 关联的 .json 文件。
对于冗长的代码块,我很抱歉,我试图尽可能地压缩,但结果仍然相当冗长。
import json
import os.path
class JDict(dict):
def __init__(self, filepath, *args, **kwargs):
if str(filepath).split('.')[-1] == 'json':
self.filepath = str(filepath)
else:
self.filepath = str('{}.json'.format(filepath))
if os.path.isfile(self.filepath):
super(JDict, self).__init__(self.read())
else:
super(JDict, self).__init__(*args, **kwargs)
self.write()
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
self.write()
def write(self):
with open(self.filepath, 'w') as outfile:
json.dump(self, outfile, sort_keys = True, indent = 4,
ensure_ascii=False)
def read(self):
with open(self.filepath, 'r') as infile:
jsonData = json.load(infile)
self = jsonData
return self
def parseJson(filepath):
with open(filepath, 'r') as infile:
jsonData = json.load(infile)
return jsonData
test = JDict("test.json", {
"TestList": [
"element1"
]
})
test["TestList"].append("element2")
try:
if test["TestList"][1] == parseJson("test.json")["TestList"][1]:
print 'Success'
except IndexError:
print 'Failure'
【问题讨论】:
-
我试过了,效果很好。
-
它没有将“失败”打印到控制台?它打印“成功”?我以不会崩溃的方式编写它......它只是根据它模仿我希望它实现的行为来打印成功或失败。 @SergeyGornostaev
-
打印'Success'和json变化。
-
@SergeyGornostaev 你用的是什么版本的python?因为这似乎不对。我一直在做一些测试,
dict.__setitem__甚至没有在dict.list.append()上触发,至少在 python 27 中没有 编辑:刚刚在 python3 中启动仍然无法正常工作。 :( -
test["TestList"].append("element2")不会触及self.__setitem__(),因为您读取 TestList 但从未写入它。之后添加一个 test["TestList"] = test["TestList"] 它应该可以工作。
标签: python json python-2.7 dictionary subclass