Sending JSON from the backend
We are going to send content in JSON format from the backend and consume it at the frontend. In addition, we will give the code a reusable structure that will be useful throughout the book.
All the code for the example can be found at https://github.com/PacktPublishing/Building-SPAs-with-Django-and-HTML-Over-the-Wire/tree/main/chapter-3/Sending%20JSON.
We have a consumer type adapted for the purpose of sending or receiving JSON called JsonWebsocketConsumer
. It is the same as WebsocketConsumer
except for two differences:
- We need to add the
send_json
function to encode to JSON:book = { 'title': 'Don Quixote', author': 'Miguel de Cervantes'. } self.send_json(content=book)
- We have a new event, called
receive_json
, which automatically decodes JSON when a message is received from the client:def receive_json(self, data): """...