我收到一个json消息/事件,类型混乱,如:
{
"AdminCreateUserConfig": {
"UnusedAccountValidityDays": "7",
"AllowAdminCreateUserOnly": "true"
}
...
}
我发现最好的方法是使用自定义序列化程序进行序列化和反序列化
代码:
event = json.loads( json.dumps(event, mySerializer) )
def mySerializer(o):
if isinstance(o, unicode):
if o in ["true", "True"]: return True
elif o in ["false", "False"]: return False
else:
try:
return int(o)
except:
return o
else:
return o.__dict__
但我的问题是,在序列化和反序列化之后,我仍然得到相同的字符串/Unicode:
AdminCreateUserConfig.UnusedAccountValidityDays: 7, type: <type 'unicode'>
AdminCreateUserConfig.AllowAdminCreateUserOnly: true, type: <type 'unicode'>
我该换什么?你知道吗
TLDR:我在AWS Lambda中,我有json对象,这就是为什么我需要再做两次转换。你知道吗
为了在解码时访问对象的键值对,您需要定义一个^{} 方法:
你可以这样使用:
object_hook
方法(或提供一个自定义的JSONDecoder
类)将只为对象调用,而不会为对象的键和值调用。你知道吗使用棉花糖
如果您的数据格式良好,最好使用marshmallow这样的库,它已经处理了这样的情况。要使用它,您需要定义一个模式:
然后可以调用加载来反序列化:
相关问题 更多 >
编程相关推荐