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

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

问题描述

我有一个Python 3.5程序来创建对象的库存。我创造了一系列蹦床(颜色,尺寸,弹簧等)。我会不断创建类的新实例,然后保存它们的字典。字典如下所示:

  my_dict = {name:instance},类型如下{string:object } 

我的问题是我想知道如何保存此清单,以便我可以开始我最后一次关闭了程序,我离开了。



我不想使用pickle,因为我正在尝试学习安全的方式来做到这一点未来更重要的版本。



我以为使用SQLite3,所以有关如何轻松实现的任何提示将不胜感激。



我的首选解决方案将说明如何使用json模块。我尝试了,但是我遇到的错误是

  __ main __。0x00032432 ...的蹦床对象不是JSON可序列化

编辑:



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

  out_file = open(input(你想要保存为什么?),w )
json.dump(my_dict,out_file,indent = 4)
out_file.close()

编辑结束



我做了大量的研究,看到许多这些SAVE选项还有一个问题,你可以只能对每个保存文件执行一个对象,但是解决这个问题的方法是使用对象的字典,例如我所做的一个对象。任何澄清这个信息的信息也会很棒!



谢谢!

解决方案

p>这是一个处理datetime对象的类的例子。

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

当你编码到json时,$ code> cls 的函数的调用与你传递的对象一起调用。如果要处理不属于标准 json.JSONEncoder.default 的类型,那么您需要拦截它并返回您希望将其处理为有效的json类型。在这个例子中,我将 datetime 转换成 str 并返回。如果它不是我想要的特殊情况之一,我只是将它传递给标准的 json.JSONEncoder.default 处理程序。



要使用此类,您需要在 cls 参数 json中传递它。转储 json.dumps

  json.dumps(obj,cls = CustomEncoder)

解码以相同的方式完成,但使用 json.JSONDecoder json.load json.loads 。但是,您无法在类型上匹配,因此您需要在编码中添加提示以进行解码,或者知道需要解码哪种类型。


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.

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.

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

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

EDIT:

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()

END of EDIT

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!

Thanks!

解决方案

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)

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.

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

json.dumps(obj, cls=CustomEncoder)

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.

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

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