簡體   English   中英

無法使用jsonpickle將json字符串解碼為python對象

[英]Unable to decode a json string to a python object using jsonpickle

我的班級結構如下 -

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

我在創造一個物體

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

並將此對象傳遞給定義,其中我使用jsonpickle.encodejsonpickle.decode如下

>>>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'>

我不明白為什么我無法將它解碼回原始對象,即使區別py/object也存在。

任何人都可以建議我做錯了什么?

添加生成上述用例的動態類的代碼。

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

這里的主要問題是,類在解碼時不可用,因此無法將其解碼為python對象。

根據JsonPickle文檔( http://jsonpickle.github.io/#module-jsonpickle ),對象必須可以通過模塊全局訪問,並且必須從對象繼承(AKA新式類)。

因此遵循以下配方, http://code.activestate.com/recipes/82234-importing-a-dynamically-generated-module/ 使用此方法,您可以生成動態模塊並動態加載類。 通過這種方式解碼類將是可訪問的,因此您可以將其解碼回python對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM