简体   繁体   中英

Why can't I open() and parse() this JSON file in Javascript?

I am using Django to build a web serivce in Python and one of my tasks is to parse a .json file within my project.

The code compiles but the var json_data trying to hold the data becomes null when I try 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
         // [
         //     { y: 450 },
         //     { y: 414},
         //     { y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle" },
         //     { y: 460 },
         //     { y: 450 },
         //     { y: 500 },
         //     { y: 480 },
         //     { y: 480 },
         //     { y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross" },
         //     { y: 500 },
         //     { y: 480 },
         //     { y: 510 }
         // ]
     }]
   });
   chart.render();

 }
</script>

</head>

The sample json data looks like:

{"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},

文件结构

So many issues here...
I'm assuming your code is expected to call the open() python function and on this case you cannot call it from javascript context as it will be evaluated to window.open() (which has nothing to do with python) rather than python function.

So all you have to do is read json file from view and return back to template context as serialized json string, something like this:

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 just use JSON.parse() . Another option is rely on $.getJSON() if you are using jQuery or similar library or AJAX, fetching json data from server via HTTP (it requires json file has public access via HTTP).

in javascript open() is for opening URL in new tab/window not reading the content, use XMLHttpRequest() or jQuery $.ajax() / .getJSON() . or you mean want to do python open() ?

code for javascript

window.onload = function() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
      // proccess json 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)
  ....
  ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM