saving and loading objects from file using jsonpickle

后端 未结 3 2039
迷失自我
迷失自我 2021-02-02 12:14

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(         


        
3条回答
  •  余生分开走
    2021-02-02 12:35

    Make sure that use_jsonpickle == True in json_load_file(). It seems that you serialize using jsonpickle and load using json.

    >>> import jsonpickle
    >>> class A(object):
    ...    def __init__(self, name):
    ...       self.name = name
    ... 
    >>> js = jsonpickle.encode(A('abc'))
    >>> js
    '{"py/object": "__main__.A", "name": "abc"}'     # <-- json string
    >>> a = jsonpickle.decode(js)
    >>> a
    <__main__.A object at 0x7f826a87bd90>            # <-- python object
    >>> a.name
    u'abc'
    >>> import json
    >>> b = json.loads(js)
    >>> b
    {u'py/object': u'__main__.A', u'name': u'abc'}    # <-- dictionary
    

    Make sure that object type is available

    >>> del A
    >>> c = jsonpickle.decode(js)                  # no type available
    >>> c
    {u'py/object': u'__main__.A', u'name': u'abc'}
    >>> type(c)
    
    >>> class A(object):
    ...    def __init__(self, name):
    ...        self.name = name
    ... 
    >>> d = jsonpickle.decode(js)                   # type is available
    >>> d
    <__main__.A object at 0x7f826a87bdd0>
    >>> type(d)
    
    

提交回复
热议问题