Rename deseralized fields in Colander

477 views Asked by At

I'm using Colander to convert JSON strings to Python Objects and vice versa in a Pyramid/Cornice based project.

Is there any way that you can serialize/deserialize to different names/keys ?

Here is the Colander Schema:

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

And here is the input JSON

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

It is being converted to :

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

Here is my question, can I have the same input JSON converted to the following?

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

Thanks for your help.

1

There are 1 answers

0
Majid On BEST ANSWER

I eventually had to do it manually. Whatever is received from the JSON is used to construct a Data Object. The Object would have a custom function to map the data to the desired output format, and you pass the output to the serializer:

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)

And the DataObject would look like this:

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