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
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.
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.
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).
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.