Reputation: 1056
We're storing raw JSON data in our model via a TextField and would like that data to be served by the REST Framework API.
The content is gettings escaped and rendered as a string rather than as part of the object. e.g. {\r\n \"phases\": [\r\n \"S
etc
from requirements.txt
Django==1.8.2
djangorestframework==3.1.3
Upvotes: 4
Views: 3060
Reputation: 1056
Added the following to my serializer (and import json
at the top of my urls.py)
def to_representation(self, instance):
ret = super(RoadmapSerializer, self).to_representation(instance)
ret['jsonField'] = json.loads(ret['jsonField'])
return ret
nb: jsonField
is the name of the model attribute declared in models.py
jsonField = models.TextField(verbose_name="JSON", blank=True)
Sources of inspiration - django-rest-framework: How Do I Serialize a Field That Already Contains JSON? (answers by Almalki and Denis Cornehl) - http://www.django-rest-framework.org/topics/3.0-announcement/#serializers (since transform_ was deprecated in drf 3.0)
Upvotes: 3