Show the text from a Json file in Django template

I am starting learn django,I have made some basic templates/views and want to show the text from a json file located in the assets/jsons folder.The file is called "quotes.json" The content of the json file:

{
  "emp_details": [
    {
      "emp_name": "johnny",
      "email": "example1.mail@gmail.com",
      "job_profile": "intern"
    },
    {
      "emp_name": "gustav",
      "email": "gustav.empl@gmail.com",
      "job_profile": "developer"
    },
    {
      "emp_name": "emily",
      "email": "emily@gmail.com",
      "job_profile": "Full Time"
    }
  ]
}

here is the views.py:

from django.http import HttpResponse
from django.shortcuts import render


from django.contrib.auth import get_user_model


#from . import models

def homepage(request):
    ##here is where I want to have the json data
    ##and return it in the render along with the request and 'homepage.html'

    return render(request,'homepage.html')

def about(request):
    return render(request,'about.html')

def users(request):

    User = get_user_model()
    users = User.objects.all()


    return render(request,'users.html',{'users':users})


here is the homepage.html ,the layout.html has css and some navigation buttons it is irrelevant. I literally only want the contents of the json to be shown as text in the homepage.

{% extends 'layout.html' %}




{% block title %}
    Home
{% endblock %}


{% block content %}


{% load static %}







{% load static %}
<script type="text/javascript">

        console.log(json1_data);
    </script>


    <h1>Home</h1>

    <h1><p>Welcome {{request.user}}</p></h1>





    <p>Check out my <a href="/about">About</a> page.</p>


    <p  id="demo"> </p>






{% endblock %}

I tried importing the file with basic python but did nor really have much success

One way to do this is to write the logic in your views to read the file and deserialize it using json.load, then pass the context to the template to be rendered:

from django.shortcuts import render
import json


def homepage(request):
    with open('assets/jsons/quotes.json') as json_file:
        data = json.load(json_file)
    return render(request, 'homepage.html', {'data': data})

Then in your template homepage.html:

{% block content %}

{% for item in data.emp_details %}
<section>
<p><strong>{{ item.emp_name }}</strong></p>
<p>{{ item.email }}</p>
<p>{{ item.job_profile }}</p>
</section>
{% endfor %}

{% endblock content %}

Lastly your urls.py:

from django.urls import path

from . import views


urlpatterns = [
    path('', views.homepage, name='home'),
  
]

This will return:


johnny

example1.mail@gmail.com

intern


gustav

gustav.empl@gmail.com

developer


emily

emily@gmail.com

Full Time

I think the reason why you are not saving it in the database is because you are selecting the file from the browser and displaying its data on the page, or perhaps posting it to the backend. You need to write javascript code for this purpose like below. you need to change it for posting data to backend.

{% extends 'layout.html' %}
{% block title %}
    Home
{% endblock %}
{% block content %}
{% load static %}
<h1>Home</h1>

<div>
    <label for="jsonFile">Select JSON file:</label>
    <input type="file" id="jsonFile" accept=".json" />
    <button onclick="loadJsonFile()">Load File</button>
</div>

<div id="jsonContent">
</div>

<p>Check out my <a href="/about">About</a> page.</p>

<p  id="demo"> </p>

<script>
function loadJsonFile() {
    const fileInput = document.getElementById('jsonFile');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('Please select a file!');
        return;
    }
    
    const reader = new FileReader();
    
    reader.onload = function(e) {
        try {
            const jsonData = JSON.parse(e.target.result);
            displayJsonData(jsonData);
        } catch (error) {
            alert('JSON file could not be parsed');
        }
    };
    
    reader.readAsText(file);
}

function displayJsonData(jsonData) {
    const contentDiv = document.getElementById('jsonContent');
    
    if (jsonData.emp_details && Array.isArray(jsonData.emp_details)) {
        let html = ''; 
        jsonData.emp_details.forEach((employee, index) => {
            html += `
                <div">
                <p><strong>Name:</strong> ${employee.emp_name}</p>
                <p><strong>Email:</strong> ${employee.email}</p>
                <p><strong>Position:</strong> ${employee.job_profile}</p>
                </div>
            `;
        });
        
        contentDiv.innerHTML = html;
    } else {
        contentDiv.innerHTML = '<p>JSON format is not as expected.</p>';
    }
}
</script>
{% endblock %}
Back to Top