Python序列化问题

2024-09-29 19:32:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我收到一个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对象,这就是为什么我需要再做两次转换。你知道吗


Tags: ineventjsonfalsetruereturnif序列化
1条回答
网友
1楼 · 发布于 2024-09-29 19:32:44

为了在解码时访问对象的键值对,您需要定义一个^{}方法:

def object_pairs_hook(pairs):
    decoded_pairs = []
    for key, val in pairs:
        # python 2/3 compatability support
        try:
            type_ = unicode
        except NameError:
            type_ = str

        if isinstance(val, type_):
            if val.lower() == "true":
                val = True
            elif val.lower() == "false":
                val = False
            else:
                try:
                    val = int(val)
                except ValueError:
                    pass

        decoded_pairs.append((key, val))

    return dict(decoded_pairs)

你可以这样使用:

>>> import json
>>> json.loads('{ "hi": { "foo": "true", "bar": "2" } }', object_pairs_hook=object_pairs_hook)
{u'hi': {u'foo': True, u'bar': 2}}

object_hook方法(或提供一个自定义的JSONDecoder类)将只为对象调用,而不会为对象的键和值调用。你知道吗

使用棉花糖

如果您的数据格式良好,最好使用marshmallow这样的库,它已经处理了这样的情况。要使用它,您需要定义一个模式:

import marshmallow

class AdminCreateUserConfig(marshmallow.Schema):
    UnusedAccountValidityDays = marshmallow.fields.Int()
    AllowAdminCreateUserOnly = marshmallow.fields.Bool()

class MySchema(marshmallow.Schema):
    AdminCreateUserConfig = marshmallow.fields.Nested(AdminCreateUserConfig)

然后可以调用加载来反序列化:

>>> MySchema().loads('{ "AdminCreateUserConfig": { "UnusedAccountValidityDays": "7", "AllowAdminCreateUserOnly": "true" } }')
{'AdminCreateUserConfig': {'UnusedAccountValidityDays': 7, 'AllowAdminCreateUserOnly': True}}

相关问题 更多 >

    热门问题