2

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"}]
3
  • You must write a custom serializer. Pagination does something like this, look at the sources of rest_framework.pagination.PaginationSerializer for inspiration. Commented Jun 26, 2014 at 14:40
  • This is a little against DRY because you probably already have the information about the model on the URL. Your URL is probably something like /api/books, so clients can derive the type of object from that. Probably this is why the framework has no provision for it. Commented Jun 26, 2014 at 14:45
  • Yes, but I want to use it for when I'm parsing the data from the API on Android. Commented Jun 26, 2014 at 15:14

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.