How to Create Json File in Django?

Hi Dev,
This article is focused on django create json file example. This article will give you simple example of how to create json file using django. I explained simply step by step how do i serve a json file from django. you can understand a concept of django create and output json file from view.
There are several ways to create text file in django. we will use HttpResponse and pass the argument content_type='application/json'. so let's see the below examples.
You can use these examples with django3 (django 3) version.
let's see below simple example with output:
Step 1 : Create a ProjectIn this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:
django-admin startproject exampleStep 2 : Create a App
python3 manage.py startapp coreStep 3 : Update setting.py
Here, do not forget to register the new app in the settings.py file. Under installed apps, just add ‘core’ to the list:
.... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ]Step 4 : Creating the Views
In this step, we need to create the views for performing ajax image upload to the database.Open the core/views.py file and add.
core/views.pyfrom django.shortcuts import render from django.http import HttpResponse def writetofile(request): filename = "demo.json" to_json = { "name": "Bhavesh", "age": "25" } response = HttpResponse(json.dumps(to_json), content_type='application/json') response['Content-Disposition'] = 'attachment; filename={0}'.format(filename) return responseStep 5 : Creating URLs
In this section, we’ll create the urls to access our views.Go to the urls.py core/urls.py file and update it as follows:
core/urls.pyfrom django.urls import path from . import views urlpatterns = [ path('json/', views.writetofile) ]
Next, we will require the modify the urls.py your root preoject folder lets update the file.
example/urls.pyfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls'), ]Run the Server
In this step, we’ll run the local development server for playing with our app without deploying it to the web.
python manage.py runserver
Next, go to the address with a web browser.
http://localhost:8000/json/
I Hope It will help you....