【问题标题】:Python 2.7 problems with sub-classing dict and mirroring to jsonPython 2.7 子类化 dict 和镜像到 json 的问题
【发布时间】: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


【解决方案1】:

所以我遇到麻烦的原因是,当您将元素附加到成员列表时,没有在字典(甚至在列表中)调用 setitem

太好了……如果其他人也有这个问题;我最终对 list 和 dict 数据类型进行了子类化,并将它们变成了一个名为 QJson 的新类的辅助类

帮助类 QJson 下的所有列表和字典分别转换为 JDicts 和 JLists。

而 QJson 本身就是一个字典

此时代码真的很长而且很单一,所以这里是我的github享受的链接。 :)

【讨论】:

    猜你喜欢
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2016-02-18
    • 2020-05-16
    相关资源
    最近更新 更多