RuSs
RuSs

Reputation: 789

django restframework: How to add an array name

Lets say I have a simple django model:

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')

When I display info from it as JSON through the django web framework I get this:

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

How would I add an array title to the generated JSON? Like so:

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

Upvotes: 2

Views: 248

Answers (1)

Paulo Scardine
Paulo Scardine

Reputation: 77251

So your client API requires the JSON to be an object instead of an array (there was a security rationale for it when using the browser built-in javascript parser to parse JSON but I forgot the reason)...

If your client API does not mind the extra fields added by PaginationSerializer, you can do:

class BookSerializer(pagination.BasePaginationSerializer):
    results_field = "books"

class BookListView(generics.ListAPIView):
    model = Book
    pagination_serializer_class = BookSerializer
    paginate_by = 9999

This will result:

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

[update]

The security reason for avoiding an array as the JSON root is JSON Hijacking. Basically, a clever hacker could override the array constructor in order to do nasty things. Only relevant if your API are answering GET requests and using cookies for authentication.

Upvotes: 3

Related Questions