【问题标题】:Why can't I open() and parse() this JSON file in Javascript?为什么我不能在 Javascript 中打开()和解析()这个 JSON 文件?
【发布时间】:2018-11-25 02:27:31
【问题描述】:

我正在使用 Django 在 Python 中构建一个 Web 服务,我的任务之一是在我的项目中解析一个 .json 文件。

代码可以编译,但是当我尝试访问 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>

示例 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},

【问题讨论】:

    标签: javascript json django


    【解决方案1】:

    在 javascript 中 open() 用于在新选项卡/窗口中打开 URL 而不读取内容,请使用 XMLHttpRequest() 或 jQuery $.ajax() / .getJSON()。或者你的意思是想做 python open()

    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)
      ....
      ....
    }
    

    【讨论】:

      【解决方案2】:

      这里有很多问题...
      我假设您的代码预计将调用 open() python 函数,在这种情况下,您不能从 javascript 上下文中调用它,因为它将被评估为 window.open()(与 python 无关)而不是 python 函数。

      所以你所要做的就是从view读取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)
      

      现在只需使用JSON.parse()。 如果您使用 jQuery 或类似的库或 AJAX,另一种选择是依赖 $.getJSON(),通过 HTTP 从服务器获取 json 数据(它要求 json 文件可以通过 HTTP 进行公共访问)。

      【讨论】:

        猜你喜欢
        • 2015-03-20
        • 2011-07-11
        • 2015-09-17
        • 2011-01-16
        • 2015-09-12
        • 2013-05-01
        • 2012-06-20
        • 2011-06-11
        相关资源
        最近更新 更多