django: control json serialization

前端 未结 4 1260
执笔经年
执笔经年 2021-01-16 09:41

Is there a way to control json serialization in django? Simple code below will return serialized object in json:

co = Collection.objects.all()
c = serializer         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-16 09:58

    That's really easy. Quick example:

    from django.http import HttpResponse
    from django.utils import simplejson
    
    def simple_view(request):
        response = {'string': "test",
                    'number': 42,
                    'array': [1, 2, 3],
                    'js_object': dict(foo="bar")}
        return HttpResponse(simplejson.dumps(response),
                            mimetype="application/json")
    

    This view will return the equivalent of the following JSON:

    {"string": "test",
     "number": 42,
     "array": [1, 2, 3],
     "js_object": {foo: "bar"}}
    

    EDIT: And yes, Assaf Lavie is right, your template can spew invalid JSON.

提交回复
热议问题