django: control json serialization

前端 未结 4 1237
执笔经年
执笔经年 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.

    0 讨论(0)
  • 2021-01-16 09:58

    Rather than writing anything yourself, let Piston do the work of serializing Django models to JSON. By default it just serializes the model's fields, no metadata. And you can easily list which fields--even related fields--to include or exclude. No extra templates, and very little view code.

    0 讨论(0)
  • 2021-01-16 10:08

    I would suggest you use the json library to encode your data, instead of just constructing the json-like string yourself. The code above doesn't seem to handle escaping properly, for one thing. And there's not much to gain by writing your own serializer (except for bugs).

    0 讨论(0)
  • 2021-01-16 10:25
    def view( request):
        m_all = list(model.objects.all().values())
    
        return HttpResponse(simplejson.dumps(m_all))
    

    This should solve the problem. Using values() and converting to list should produce the result you wanted.

    0 讨论(0)
提交回复
热议问题