Wednesday, 15 April 2015

json - django restframework: How to add an array name -



json - django restframework: How to add an array name -

lets have simple django model:

class snippet(models.model): created = models.datetimefield(auto_now_add=true) title = models.charfield(max_length=100, blank=true, default='')

when display info json through django web framework this:

[{"id": 1, "title": "hello"}, {"id": 2, "title": "world"}]

how add together array title generated json? so:

["books" :{"id": 1, "title": "hello"}, {"id": 2, "title": "world"}]

so client api requires json object instead of array (there security rationale when using browser built-in javascript parser parse json forgot reason)...

if client api not mind fields added paginationserializer, can do:

class bookserializer(pagination.basepaginationserializer): results_field = "books" class booklistview(generics.listapiview): model = book pagination_serializer_class = bookserializer paginate_by = 9999

this result:

{ 'count': 2, 'next': null, 'previous': null, 'books': [ {"id": 1, "title": "hello"}, {"id": 2, "title": "world"} ] }

[update]

the security reason avoiding array json root json hijacking. basically, clever hacker override array constructor in order nasty things. relevant if api answering requests , using cookies authentication.

json django django-models django-rest-framework

No comments:

Post a Comment