1

Here is my model:

class Question(models.Model):
    options = models.TextField()

Here is the serializer:

class QuestionSerializer(ModelSerializer):
    class Meta:
        model = Question

Here is the view:

class QuestionView(ListAPIView):
    queryset = Question.objects.all()
    renderer_classes = (JSONRenderer,) 
    serializer_class = QuestionSerializer

Inside the database, an available record looks like this:

id  options
1   [u'opt1', u'opt2']

When the api is requested, here is the returned JSON:

{
  "id": 1,
  "options": "[u'opt1', u'opt2']"
}

My question is how to save a string in JSON format and retrieve it in JSON format without the unicode prefix? (I need to support unicode characters, so I cannot simply convert the data submitted by users to string)


Update: Here is one solution that I have found so far. Use django-jsonfield to define your field:

from jsonfield import JSONField

class Question(models.Model)
    options = JSONField()

Then, define a custom serializer field:

from rest_framework import serializers

class JsonField(serializers.Field):
    def to_representation(self, value):
        return value

    def to_internal_value(self, data):
        return data

Use this field in a serializer:

class QuestionSerializer(ModelSerializer):
    options = JsonField()

    class Meta:
        model = Question

Now if you try to store and then retrieve a record from the database, you should get a JSON formated string back without the unicode prefix.

Since django-jsonfield is looking for maintainers ATM, just in case it becomes obsolete, here are the versions I am using:

  • Django 1.8.7
  • django-jsonfield 1.0.3
  • PostgresSQL 9.4.0.1
Cheng
  • 16,824
  • 23
  • 74
  • 104
  • Check this answer https://stackoverflow.com/questions/34038367/i-am-sending-json-data-to-api-but-getting-unicode-json-data-whe-api-call-from-an/34039096#34039096 – Geo Jacob Dec 08 '15 at 10:37

1 Answers1

1

Encode the unicode strings in UTF-8. The unicode prefix will be gone and the string will still support unicode characters:

>>> msg = u"Hello"

>>> msg = msg.encode("utf-8")

>>> msg

'Hello'

Since you'll need to convert all the values in a dict, you'll probably need to write a function to do that. But it's been taken care of here: How to get string objects instead of Unicode ones from JSON in Python?

Community
  • 1
  • 1
xyres
  • 20,487
  • 3
  • 56
  • 85
  • This is a django-rest-framework related question. `renderer_classes = (JSONRenderer,) ` should've perform what you suggested IMO. But I am not sure why it didn't work. – Cheng Dec 08 '15 at 12:20