I want to return the result in JSON
following this format:
{"cadastros": [
{"id": 1, "STATUS": true, "pessoas": [], "podeEscrever": true},
{"id": 2, "STATUS": false, "pessoas": ['Maria', 'Ana'], "podeEscrever": true},
], 'principal': true}
models.py :
class MyModel(models.Model):
status = models.BooleanField()
pessoas = models.ManyToManyField(Pessoa, blank=True)
podeescrever = models.BooleanField()
Note that in the format JSON
there is podeEscrever
with a capital letter, so the result should respect this format too.
The main idea is to use the simplejson
library to manipulate the result and return the JSON
in the desired format.
views.py :
def minha_views(request):
p = Pessoa.objects.values()
data = simplejson.dumps(p)
# aqui seria formatado
return HttpResponse(data, content_type='application/json; charset=utf8')
My difficulty is to format JSON
, I can return query results straight to JSON
, but I do not know how to manipulate it to add new keys and change the name of field podeescrever
to podeEscrever
.
pessoas
field that is ManytoManyField
does not return in JSON
if it is empty, the correct one was to return with an empty list []
if there are no items.
It does not seem difficult to do this, does anyone know how to solve this problem?