Django: Control Json Serialization
Solution 1:
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.
Solution 2:
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).
Solution 3:
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.
Solution 4:
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.
Post a Comment for "Django: Control Json Serialization"