Creating a JSON response using Django and Python

In this tutorial, we will learn to create JSON responses using Django & Python for web applications. We can use it to make Python return JSON responses in Django.
Submitted by Apurva Mathur, on May 26, 2022

JSON Response

It stands for JavaScript Object Notation. It is a human and machine readable format to represent data as structured data. It is specifically used to transfer the data from one computer to another or we can say transfer the code from one medium to another that medium can be both within same machine or different machines.

Important things to keep in mind while defining JSON:

  • Key-value pairs are separated by a : (colon)
  • Key is always present in Double Quotes " "
  • Value could be anything depending on the Data Type

Values of Data type in JSON:

  • Boolean: True or False
  • Number: Numerical values
  • Object: An associative array of Key-Value pairs
  • Array: Associative array of just values

Syntax of JSON – How JSON are represented in Python?

{"Department":"Computer science"}

In Django, the first step is to import the JsonResponse function.

Example:

import json

from django.http import HttpResponse

def create_json(request):
    new_json = {
        'serial_number': 1,
        'Department': 'computer science',
    }
    
    return HttpResponse(json.dumps(new_json) ,content_type="application/json")

After importing the JSON package, we define an object commonly called a JSON object, here in the above example that object is new_json which is defined inside the function named create_json. It will return the object in JSON form as we have imported the package HttpResponse. The content-type argument needs to be "applications/json" because the response which is generated with this piece of code is in JSON format.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.