使用jsonpickle保存和加载文件中的对象 [英] saving and loading objects from file using jsonpickle

查看:228
本文介绍了使用jsonpickle保存和加载文件中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几种使用jsonpickle将python对象写入文件的简单方法:

I have the following simple methods for writing a python object to a file using jsonpickle:

def json_serialize(obj, filename, use_jsonpickle=True):
    f = open(filename, 'w')
    if use_jsonpickle:
        import jsonpickle
        json_obj = jsonpickle.encode(obj)
        f.write(json_obj)
    else:
        simplejson.dump(obj, f) 
    f.close()

def json_load_file(filename, use_jsonpickle=True):
    f = open(filename)
    if use_jsonpickle:
        import jsonpickle
        json_str = f.read()
        obj = jsonpickle.decode(json_str)
    else:
        obj = simplejson.load(f)
    return obj

问题是,每当我使用这些对象时,它就会将我的对象作为字典(具有诸如"py/object":"my_module.MyClassName"之类的字段)的形式加载回去,而不是作为所使用类型的实际Python对象生成json字符串.我该如何做,以便jsonpickle实际上将加载的字符串转换回该对象?

the problem is that whenever I use these, it loads my objects back as dictionaries (that have fields like: "py/object": "my_module.MyClassName") but not as an actual Python object of the type that was used to generate the json string. How can I make it so jsonpickle actually converts the loaded string back to the object?

以一个示例来说明这一点,请考虑以下内容:

to illustrate this with an example, consider the following:

class Foo:
    def __init__(self, hello):
    self.hello = hello

# make a Foo obj
obj = Foo("hello world")
obj_str = jsonpickle.encode(obj)
restored_obj = jsonpickle.decode(obj_str)
list_objects = [restored_obj]
# We now get a list with a dictionary, rather than
# a list containing a Foo object
print "list_objects: ", list_objects

这将产生:

list_objects:  [{'py/object': 'as_events.Foo', 'hello': 'hello world'}]

而不是类似:[Foo()].我该如何解决?

Rather than something like: [Foo()]. How can I fix this?

谢谢.

推荐答案

正确的答案是我不是从object继承.似乎没有从object继承,jsonpickle无法正确解码在构造函数中带有一个或多个参数的类.我绝不是专家,但是在类声明中将其固定为Foo(object):而不是Foo:.

The correct answer was that I was not inheriting from object. Without inheriting from object, jsonpickle cannot correctly decode classes that take one or more arguments in the constructor, it seems. I am by no means an expert but making it Foo(object): rather than Foo: in the class declaration fixed it.

这篇关于使用jsonpickle保存和加载文件中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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