问题描述
jsonpickle中对此有任何支持吗?
Is there any support of this in jsonpickle?
例如我存储并反对,他们修改了其架构,然后尝试将其加载回去.
E.g. I store and object, them modify its schema, then try to load it back.
例如,以下更改(属性添加)
The following change, for instance, (attribute addition)
import jsonpickle
class Stam(object):
def __init__(self, a):
self.a = a
def __str__(self):
return '%s with a=%s' % (self.__class__.__name__, str(self.a))
js = jsonpickle.encode(Stam(123))
print 'encoded:', js
class Stam(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return '%s with a=%s, b=%s' % (self.__class__.__name__, str(self.a), str(self.b))
s=jsonpickle.decode(js)
print 'decoded:', s
产生错误:
encoded: {"py/object": "__main__.Stam", "a": 123}
decoded: Traceback (most recent call last):
File "C:\gae\google\appengine\ext\admin\__init__.py", line 317, in post
exec(compiled_code, globals())
File "<string>", line 25, in <module>
File "<string>", line 22, in __str__
AttributeError: 'Stam' object has no attribute 'b'
推荐答案
jsonpickle中不支持类型演变或类型迁移.
There is no support for type evolution or type migrations within jsonpickle.
您最好的做法是将数据的JSON表示(通过json.loads
加载)到列表/字典/字符串/数字的基本Python结构中.遍历此Python表示形式,添加空/默认b
键.然后通过json.dumps
重新保存JSON.
Your best course of action would be to load (via json.loads
) the JSON representation of your data into a basic Python structure of lists / dicts / strings / numbers. Traverse this Python representation, adding in empty/default b
keys. Then re-save the JSON via json.dumps
.
然后您可以使用jsonpickle加载数据的修改版本.
You can then use jsonpickle to load the modified version of the data.
temp = json.loads(js)
temp['b'] = None
js = json.dumps(temp)
jsonpickle.decode(js)
如果您的对象模型更复杂,这显然会变得更加复杂,但是您可以检查py/object键以查看是否需要修改对象.
This obviously gets more complicated if your object model is more complex, but you can check the py/object key to see if you need to modify the object.
这篇关于使用jsonpickle进行类型演变(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!