簡體   English   中英

為什么我不能用Javascript打開()和解析()這個JSON文件?

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

我正在使用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},

文件結構

這里有很多問題...
我假設您的代碼應該調用open() python函數,在這種情況下,您將無法從javascript上下文調用它,因為它將被評估為window.open() (與python無關),而不是python功能。

因此,您要做的就是從視圖中讀取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的公共訪問權限)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM