Convert JSON data into an array in Django

This tutorial is to convert JSON data into an array in Django and print the same. We will create JSON Data and then we will use the dumps function.

To do this task, we need JSON data, JSON means JavaScript Object Notation. We will create json data to convert it into an array.

Steps to follow-

  1. Create a project.
  2. Start an app.
  3. Define URL.
  4. Create a function to convert.
  5. Run your server.

The first two steps are very common and I hope you know how to start a project and an app, we will proceed further on defining URL to navigate, and then we will create a function in our views.py.

Define a URL

Moving towards urls.py, we need to specify the path or it is known as a pipeline in Django. Open urls.py and make further changes-

path('',views.json_array),

Don’t forget to import views from the app as – from app import views

urls.py should look like-

from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.json_array),
]

We have defined URL, now as we have specified the path we need to make the function at the destination to convert JSON data into an array and print it at the output screen.

Create a function json_array in views.py

Without any further delay, let’s move to the views.py file and create a function to convert JSON string to an array.

Open your views.py under your app-

def json_array(request):
    info={
  "Students": [
    {
      "Name": "Tina",
      "Age": 17,
      "City": "Narsinghpur",
      "Birthday": "March 24, 2005",
      
    },
    {
      "Name": "Atharv",
      "Age": 7,
      "City": "Bhopal",
      "Birthday": "April 7, 2015",
      
    }
  ]
}
    
    x = json.dumps(info,indent=2)



    
    return HttpResponse(x,content_type="text/plain")

Also import json at the top. We have successfully converted our JSON data into an array.

Just run your server using – python manage.py runserver

You will see your screen as-

Convert JSON data into an array in Django

I hope you have understood this tutorial well! Feel free to share your reviews!

Leave a Reply

Your email address will not be published.