Harsh Shah
Harsh Shah

Reputation: 182

What is the difference between json.dumps() and JSONRenderer.render() methods?

I am learning Django Rest Framework. I came up across method JSONRenderer.render() which takes python objects and converts them to JSON string.

But why do not we use json.dumps() method for this. Why to create another method which does the same work?

Upvotes: 1

Views: 624

Answers (1)

Pavel Vergeev
Pavel Vergeev

Reputation: 3380

json.dumps is a standard library function that converts a dictionary into a JSON string.

JSONRenderer is a Django REST Framework renderer. Renderer is a class responsible for making sure your clients get a correctly-formatted HTTP response. That is, that the response is a valid HTTP response, with a correct Content-Type header and other things like that. DRF allows you to use different renderers, because you might as well have sent an XML response, or a binary. All of them need to be formatted into a correct HTTP response.

JSONRenderer does need to convert a dictionary to JSON in order to fulfil its purpose, but that's not all it does. This class is aware that it's used in an HTTP context, while json.dumps is a generic function that purposely lacks this context so you could use it everywhere.

Upvotes: 1

Related Questions