使用jsonpickle从文件中保存和加载对象

18 python serialization json jsonpickle

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

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
Run Code Online (Sandbox Code Playgroud)

问题是,无论何时我使用它们,它都会将我的对象作为字典(具有类似"py/object":"my_module.MyClassName")的字段加载回来,而不是用作生成的类型的实际Python对象json字符串.我怎么能这样做jsonpickle实际上将加载的字符串转换回对象?

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

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
Run Code Online (Sandbox Code Playgroud)

这会产生:

list_objects:  [{'py/object': 'as_events.Foo', 'hello': 'hello world'}]
Run Code Online (Sandbox Code Playgroud)

而不是像:[Foo()].我怎样才能解决这个问题?

谢谢.

小智 22

正确的答案是我没有继承object.在没有继承的情况下object,jsonpickle无法正确解码构造函数中包含一个或多个参数的类.我绝不是专家,Foo(object):而是Foo:在课堂宣言中修改它而不是它.