3

Pyramid/Cornice ベースのプロジェクトで、Colander を使用して JSON 文字列を Python オブジェクトに、またはその逆に変換しています。

異なる名前/キーにシリアル化/逆シリアル化できる方法はありますか?

水切りスキーマは次のとおりです。

class CommentSchema(MappingSchema):
    resource_id = SchemaNode(Int(), name="resourceID", location="body")
    text = SchemaNode(String(), name="text", location="body")

そして、ここに入力JSONがあります

{"text":"Hello!", "resourceID":12}

それはに変換されています:

{u'text': u'Hello!', u'resourceID': 12}

これが私の質問です。同じ入力 JSON を次のように変換できますか?

{u'full_text': u'Hello!', u'resource_id': 12}

ご協力いただきありがとうございます。

4

1 に答える 1

1

最終的に手動で行う必要がありました。JSON から受信したものはすべて、データ オブジェクトの構築に使用されます。オブジェクトには、データを目的の出力形式にマップするカスタム関数があり、出力をシリアライザーに渡します。

data_schema = DataSchema().deserialize(self.request.json)
data_obj = DataObject(data_schema**) // or DataObject(full_text = data_schema['text'], resource_id = data_schema['resourceID'])
#
# ...
#
rbody = DataSchema().serialize(data_obj.map_dump())
return Response(body=rbody, status_code=201)

DataObject は次のようになります。

class DataObject(Object):

    def __init__(self, text, resourceID):  // or __init__(self, full_text, resource_id)
        self.text = text
        self.resourceID = resourceID

    def map_dump(self):
        output['full_text'] = self.text
        output['resource_id'] = self.resource
        return output
于 2015-01-07T19:07:05.877 に答える