简体   繁体   English

为什么我不能用Javascript打开()和解析()这个JSON文件?

[英]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. 我正在使用Django在Python中构建Web服务,我的任务之一是在项目中解析.json文件。

The code compiles but the var json_data trying to hold the data becomes null when I try to access the json file. 代码可以编译,但是当我尝试访问json文件时,试图保存数据的var json_data变为null。

<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: 样本json数据如下所示:

{"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. 我假设您的代码应该调用open() python函数,在这种情况下,您将无法从javascript上下文调用它,因为它将被评估为window.open() (与python无关),而不是python功能。

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: 因此,您要做的就是从视图中读取json文件,并以序列化的json字符串形式返回模板上下文,如下所示:

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() . 现在只需使用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). 如果您使用的是jQuery或类似的库或AJAX,则另一个选择是依赖$ .getJSON() ,它通过HTTP从服务器获取json数据(它要求json文件具有通过HTTP的公共访问权限)。

in javascript open() is for opening URL in new tab/window not reading the content, use XMLHttpRequest() or jQuery $.ajax() / .getJSON() . 在javascript中, open()用于在新标签页/窗口中打开不读取内容的URL,请使用XMLHttpRequest()或jQuery $.ajax() / .getJSON() or you mean want to do python open() ? 还是您想做python open()

code for javascript 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)
  ....
  ....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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