簡體   English   中英

Python序列化問題

[英]Python serialization issue

我收到的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_pairs_hook方法:

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類)將僅針對對象被調用,而不會針對對象的鍵和值被調用。

使用棉花糖

如果您的數據格式正確,則最好使用像棉花糖這樣的庫,該庫已經可以處理此類情況。 要使用它,您將定義一個模式:

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

暫無
暫無

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

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