0
所以我想創建一個類似字典的類,但是每當對字典進行更改時,它也會將自身複製到.json文件。我已經在大部分工作;但是我遇到麻煩的是當我在字典裏面添加一些內容到列表中的時候;它更新字典但不是與字典關聯的.json文件。Python 2.7分類字典和鏡像到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 –
打印'成功'和json改變。 –