django-rest-framework: How Do I Serialize a Field That Already Contains JSON?

django, django-rest-framework, json, python, serialization

Solution

You can simply decode the json into python object:

json_obj = json.loads(model.json_text)

Once you serialize your object, replace this field with the decoded object:

data = serializer.data
data["field"] = json_obj
return Response(data)

Problem

I am pretty new to the django-rest-framework, so could use some help. I have an object with a TextField that is a string containing JSON. I'm using django-rest-framework to serialize the whole object as JSON. However, this one string that is already JSON gets serialized as an encoded string containing the JSON rather than the JSON itself. How can I tell the serializer to send this field as-is rather than trying to transform this string to JSON? Is there some sort of "ignore" decorator or override I can use? Or can I pre-parse this JSON before serializing? This is the difference between having: ``` {"data": data} ``` and ``` {"data": "data"} ``` The latter being more of a nuisance to use on the client side...

Original source