JSON作为Unicode添加到数据库

时间:2016-11-08 16:54:30

标签: python json django unicode

我正在尝试将JSON请求保存为数据库中的字符串但存在一些问题:由于某种原因,我的数据将作为Unicode字符串保存到数据库中。我的意思是在数据库中这样保存字符串:

[{u'content': u'Treehouse', u'name': u'opportunity_name'}, {u'content': u'Robert', u'name': u'user_firstname'}, {u'content': u'Warren', u'name': u'client_firstname'}, {u'content': u'Buffett', u'name': u'client_lastname'}, {u'content': u'Form ABC123', u'name': u'my_name'}]

当它们应该是这样的时候(没有你的):

[{'content': 'Treehouse', 'name': 'opportunity_name'}, {'content': 'Robert'...

这是我的代码,在views.py中(此处的数据也可以打印为unicode):

@csrf_exempt
def send_aggregate_list(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        print 'data'
        # the output from this print statement is the same, with leading 'u's
        print data
        serializer = SendAggregateSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(data,status=201)

models.py:

class SendAggregate(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    is_sent = models.BooleanField(default=False)
    global_merge_vars = models.TextField()
    subject_merge_vars = models.TextField()
    to_email = models.CharField(max_length=256, blank=False)
    to_name = models.CharField(max_length=256, blank=False)
    template = models.ForeignKey(Template, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return str(self.pk)

serializers.py:

class SendAggregateSerializer(serializers.ModelSerializer):
    class Meta:
        model = SendAggregate
        fields = ('id', 'created', 'is_sent', 'to_email', 'to_name', 'global_merge_vars', 'subject_merge_vars', 'template')

如果有帮助,这是serializer.validated_data的输出:

OrderedDict([(u'to_email', u'rob.grzesik@gmail.com'), (u'to_name', u'Recipient Name'), (u'global_merge_vars', u"[{u'content': u'Treehouse', u'name': u'opportunity_name'}, {u'content': u'Robert', u'name': u'user_firstname'}, {u'content': u'Warren', u'name': u'client_firstname'}, {u'content': u'Buffett', u'name': u'client_lastname'}, {u'content': u'Form ABC123', u'name': u'loan_task_subject'}]"), (u'subject_merge_vars', u'[]'), (u'template', <Template: my_name>)])

1 个答案:

答案 0 :(得分:0)

找到解决方案!只需切换到使用另一个JSON包:

import simplejson as json