Can't decode json string for python object using jsonpickle

My class structure is like this:

class HelloWorld (object):
    def __init__(self, name, i, id):
        self.name = name
        self.i = i
        self.id = id

      

I am creating an object

p = HelloWorld('pj', 3456, '1234')

      

and passing that object to definition where i use jsonpickle.encode

and jsonpickle.decode

as follows

>>>print(type(p)) 
    <class 'HelloWorld'>
 >>>x = jsonpickle.encode(p)        
 >>>print(x)
    {"i": 3456, "name": "pj", "py/object": "__builtin__.HelloWorld", "id": "1234"}
 >>>y = jsonpickle.decode(x)
 >>>print(type(y))
    <class 'dict'>

      

I don't understand why I can't decode it back to the original object even though the distinctive is present py/object

.

Can anyone suggest what I am doing wrong?

Adding code that generates a dynamic class for the above use case.

def _create_pojo(self, pojo_class_name, param_schema):

    #extracting the properties from the parameter 'schema'        
    pojo_properties = param_schema['properties']

    #creating a list of property keys
    pojo_property_list = []
    for key in pojo_properties:
        pojo_property_list.append(key)

    source = \
        "class %s (object):\n" % ( pojo_class_name )       
    source += "    def __init__(self, %s" % ', '.join(pojo_property_list) +"):\n" #defining __init__ for the class
    for prop in pojo_property_list: #creating a variable in the __init__ method for each property in the property list
        source += "        self.%s = %s\n" % (prop, prop)

    #generating the class code
    class_code = compile( source, "<generated class>", "exec" )
    fakeglobals = {}
    eval( class_code, {"object" : object}, fakeglobals )
    result = fakeglobals[ pojo_class_name ]        
    result ._source = source
    pprint.pprint(source)       

    self._object_types[ pojo_class_name ] = result
    return result

      

+3


source to share


1 answer


The main problem here is that the class is not available when decoded, so it cannot decode it as a python object.

According to the JsonPickle documentation ( http://jsonpickle.github.io/#module-jsonpickle ) the object must be globally accessible via the module and must inherit from the object (AKA new style classes).



Therefore, follow the following recipe http://code.activestate.com/recipes/82234-importing-a-dynamically-generated-module/ . With it you can generate a dynamic module and load classes dynamically. This way, when decoding, the class will be available and hence you can decode it back to a python object.

+2


source







All Articles