如何保存对象字典? [英] How to save a dictionary of objects?

查看:243
本文介绍了如何保存对象字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python 3.5程序,用于创建对象清单.我创建了Trampoline的类(颜色,大小,弹簧等).我将不断创建该类的新实例,然后保存它们的字典.字典看起来像这样:

I have a Python 3.5 program that creates an inventory of objects. I created a class of Trampolines (color, size, spring, etc.). I constantly will create new instances of the class and I then save a dictionary of them. The dictionary looks like this:

my_dict = {name: instance} and the types are like so {"string": "object"}

我的问题是我想知道如何保存此库存清单,以便在上次关闭程序时从上次中断的地方开始.

My issue is that I want to know how to save this inventory list so that I can start where I left off the last time I closed the program.

我不想使用pickle,因为我正在尝试学习安全的方法,以便将来在更重要的版本中使用它.

I don't want to use pickle because I'm trying to learn secure ways to do this for more important versions in the future.

我考虑过要使用sqlite3,所以任何有关如何轻松实现此目的的技巧都将不胜感激.

I thought about using sqlite3, so any tips on how to do this easily would be appreciated.

我的首选解决方案是说明如何使用json模块.我尝试过,但是出现的错误是:

My preferred solution would state how to do it with the json module. I tried it, but the error I got was:

__main__.Trampoline object at 0x00032432... is not JSON serializable

以下是我收到错误时使用的代码:

Below is the code I used when I got the error:

out_file = open(input("What do you want to save it as?  "), "w")
json.dump(my_dict, out_file, indent=4)
out_file.close()

编辑结束

我已经做了大量研究,发现许多 save 选项还存在一个问题,即每个"save"只能做一个对象文件",但是解决方法是您使用对象字典,例如我制作的字典.任何澄清这一点的信息也将很棒!

I've done a good amount of research, and saw that there's also an issue with many of these save options that you can only do one object per 'save file', but that the work around to this is that you use a dictionary of objects, such as the one I made. Any info clarifying this would be great, too!

推荐答案

以下是处理日期时间对象的类的示例.

Here is an example of a class that handles datetime objects.

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            if obj.tzinfo:
                obj = obj.astimezone(isodate.tzinfo.UTC).replace(tzinfo=None)
            return obj.isoformat()[:23] + 'Z'
        return json.JSONEncoder.default(self, obj)

当您编码为json时,clsdefault函数将与您传递的对象一起调用.如果要处理不属于标准json.JSONEncoder.default的类型,则需要拦截它并以有效的json类型返回要如何处理它.在此示例中,我将datetime转换为str并将其返回.如果它不是我要特殊使用的类型之一,则将其传递给标准json.JSONEncoder.default处理程序.

when you encode to json the default function of the cls is called with object you passed. If you want to handle a type that is not part of the standard json.JSONEncoder.default you need to intercept it and return how you want it handled as a valid json type. In this example I turned the datetime into a str and returned that. If its not one of the types I want to special case, I just pass it along to the standard json.JSONEncoder.default handler.

要使用此类,您需要在json.dumpjson.dumpscls参数中传递它:

To use this class you need to pass it in the cls param of json.dump or json.dumps:

json.dumps(obj, cls=CustomEncoder)

使用json.JSONDecoderjson.loadjson.loads进行解码的方法相同.但是,您无法在类型上进行匹配,因此您将需要在编码中添加提示"以进行解码,或者知道其需要解码的类型.

Decoding is done the same way but with json.JSONDecoder, json.load, and json.loads. However you can not match on type, so you will need to either add an 'hint' in encoding for decoding or know what type it needs to decode.

这篇关于如何保存对象字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆