What's preventing me from opening and parsing this JSON file using JavaScript?

In my Python Django project, I am working on creating a web service and one of the tasks involves parsing a .json file.

Although the code compiles successfully, the var json_data which is supposed to hold the data turns null when trying to access the json file.

<head>
 <meta charset="UTF-8">
 <title>Network Graph3</title>
 <link rel="stylesheet" href="{% static 'css/style.css' %}">


 <script>
  // import json;
  window.onload = function () {
   var arr = [];
   var json_data = open("{% static 'static/json/graphData.json' %}");

   var obj = JSON.parse(json_data);
   var i;
   console.log(json_data)
   if (obj == null){
     return
   }
   for (i = 0; i < obj.documents; i++){
     point = obj.documents[i];
     arr[point.id].y = point.score;
   }
   var chart = new CanvasJS.Chart("chartContainer", {
     animationEnabled: true,
     theme: "light2",
     title:{
         text: "Dialog Sentiment Analysis"
     },
     axisY:{
         includeZero: false
     },
     data: [{
         type: "line",
         dataPoints: arr
     }]
   });
   chart.render();

 }
</script>

</head>

The provided sample json data format:

{"documents": [{"id": "0", "score": 0.8365770578384399},
            {"id": "2", "score": 0.9896875619888306},
            {"id": "3", "score": 0.5},
            {"id": "4", "score": 0.5},
            {"id": "6", "score": 0.12722820043563843},
            {"id": "7", "score": 0.16494140028953552},
            {"id": "8", "score": 0.7551238536834717},
            {"id": "9", "score": 0.12901419401168823},
            {"id": "10", "score": 0.5},
            {"id": "11", "score": 0.7559014558792114},

https://i.sstatic.net/FufZSl.png

Answer №1

When it comes to JavaScript, using the open() function is ideal for opening a URL in a new tab/window rather than reading its content. For that purpose, you should resort to XMLHttpRequest(), jQuery's $.ajax(), or .getJSON(). Unless you're referring to utilizing Python's open() method?

Here's a code snippet for JavaScript:

window.onload = function() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
      // Process JSON data here
      readJson(xhr.responseText);
    }
  }
  xhr.open('GET', "/'static/json/graphData.json=", true);
  xhr.send(null);
}

function readJson(json_data) {
  var arr = [];
  var obj = JSON.parse(json_data);
  var i;
  console.log(json_data)
  ....
  ....
}

Answer №2

There are several issues to address here...
It seems like your code intends to call the open() Python function, but in this scenario, you cannot execute it within a JavaScript context. This would result in calling window.open() (which is unrelated to Python) instead of the intended Python function.

To resolve this, you should read a JSON file from a Django view and return it as a serialized JSON string back to the template context. Here's an example:

from django.shortcuts import render

def my_view(request):
    context = {"data": None}

    with open('data.json') as f:
        context['data'] = json.load(f)

    return render(request, 'templates/my_template.html', context)

Now you can simply use JSON.parse(). Alternatively, you can utilize $.getJSON() if you're using jQuery or a similar library for AJAX requests to fetch JSON data from the server over HTTP (make sure the JSON file is publicly accessible via HTTP).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The subsequent page fails to load. Issue with the pagination feature

I'm currently stuck trying to implement pagination in my task and it's not functioning as expected. My approach involved creating two buttons with click events attached, along with a data property that changes when the buttons are clicked. This ...

What causes the selected option to be hidden in React?

I created a basic form demo using react material, featuring only one select field. I followed this link to set up the select options: https://material-ui.com/demos/selects/ With the help of the API, I managed to display the label at the top (by using shri ...

There was an issue encountered while trying to submit a comment on the website: (1048, "The 'comment_post_id' column cannot have a null value")

I've been working on adding a comment section to each blog post on my website. The form is showing up correctly, but when I try to submit a comment, I'm encountering the following error: (1048, "Column 'comment_post_id' cannot be ...

Components with no specific branding in Vue

Creating a quiz in Vue.js with various question types: Select one Select multiple Select image Match The challenge lies in the mixing of question types within the same quiz, leading to the use of different components (<x-select-one-question>, < ...

send the ID of the element as an argument in jQuery

A web form I am working on contains a select box that, when a specific option is chosen, reveals a hidden div. <script> $(document).ready(function () { $("#Select1").change(function () { $(this).find("option:selected").each(function(){ ...

Combining Django with folium results in a null value being returned

I have been attempting to incorporate Folium maps into my Django application. Below is the relevant code snippet: def map(request): data = pd.DataFrame({ 'lat': [77, 75, 72, 77, 78], 'lon': [28, 26, 19, 29, 30], ...

The dynamic import() syntax is not compatible with the target environment, preventing the use of external type 'module' in a script

I am currently facing an issue with my React app. The command npm start is working as expected, but when I try to run npm run build, it keeps failing. It's crucial for me to run npm run build in order to deploy the app on a website. I have already sp ...

The error message in monodb.js at line 2: "require is not defined" indicates an issue with the 'require' statement not being

const { MongoClient } = require("mongodb") const url='mongodb://localhost:27017' const client=new MongoClient(url); async function fetchData(){ let result=await client.connect(); let db=result.db("first& ...

Using Django to access related model values within a values list query

I am currently exploring the possibility of setting up a query that functions similarly to Model.objects.values_list('id', 'related_model__ids') and returns a structure like [(1L, [2L, 6L]), (2L, [1L,]), (3L, [1L, 3L, 4L, 5L]), ...]. He ...

Rearrange div elements dynamically with JavaScript

I need help with reordering the div elements using JavaScript. Is this the correct approach? <div id="pageWrapper"> <div id="one">1</div> <div id="two">2</div> <div id="three">3</div> <div id= ...

Continuing to struggle with making an AJAX call in a standalone JavaScript file

I am currently learning about jquery and ajax, and I have a requirement to call servlet/jsp through ajax using jquery without having my ajax code in a separate javascript file. Below is the javascript function where I'm trying to make an ajax call: ...

Copying content from one website to another using JavaScript

Currently, I am working on a website which stores data and I require assistance in transferring this data to another site. If you have any suggestions using Javascript or other methods, please let me know. ...

A guide on how to alternate between ng-hide and ng-show using separate controllers by utilizing a shared factory toggle state instance

Using Angular 1.x, I have implemented two controllers where I want to display controller_2 if controller_1 is hidden. To achieve this, I am utilizing a factory method. Here is the snippet of my HTML code:- <div ng-controller="controller_1 as c1" ng- ...

What is the best way to utilize ngResource for a particular response body structure?

My reply body has the following structure: { "code": 200, "message": Data retrieved successfully, "items": [ { ... } ] } Previously, I used $http and did not encounter this issue. Howev ...

Implementing JavaScript to showcase a list extracted from an API dataset

I'm currently undertaking a project where I am integrating an API from a specific website onto my own webpage. { "data": [{ "truckplanNo":"TCTTV___0D010013", "truckplanType":"COLLECTION", " ...

Navigating through history using the pushState method and incorporating back and forward buttons

I am trying to implement back and forward buttons functionality with this ajax method The code is working well, and the URL in the browser is changing as expected However, when I click on the back and forward buttons, nothing happens (function(){ ...

"Integration of SQL functions within an Object-Relational

In my setup, I have SQL Server, FreeTDS, and Django 1.5.5. To implement SQL Server's full text search using the contains function, I am required to use the contains function of SQL Server. Specifically, I need to search for "mytext" in the x_name fie ...

The 3-way data binding in angularFire does not update a function

My issue involves a firebaseObject (MyFirebaseService.getCurrentUser()) being bound to $scope.user. Once successfully bound, I iterate through the object to check if it contains an "associatedCourseId" equal to a specific value ($stateParams.id). If it doe ...

Solution to bypass JavaScript PHP login system

Creating a login/register system with JavaScript to display specific divs for the system: 1st div = menu option to either log in or register 2nd div = shows login form or register form depending on what was clicked (login or register) 3rd div = displays ...

Best practices for retrieving information from an array of identifiers?

As of now, I am attempting to utilize a list of ID's in order to retrieve the corresponding data associated with each ID. Below is my code: export const fetchAllRoomData = createAsyncThunk( "socket/fetchAllRoomData", async ({ nspData }, ...