2017-03-01 49 views
0

我在這裏有一個JSON文檔。我已使用JSlint進行驗證。爲什麼這個JSON文件閱讀stra 012

的JSON的格式如下:

[{ 
    "date": "2017-02-10", 
    " action": "Do a thing", 
    "state": "closed", 
    "url": "https:someurl.com" 
}, 
.... 

我有一些HTML here,只存在於讀取和輸出的JSON。

的HTML看起來像這樣:

<html> 

<head> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 
</head> 

<body> 
    <script> 
     deadlines = [] 
     start(); 

     function start() { 
      var req = new XMLHttpRequest(); 
      req.open("GET", "http://joereddington.com/deadlines.json"); 
      req.overrideMimeType("application/json"); 
      req.send(null); 
      req.onreadystatechange = function() { 
       if (req.readyState == 4 && req.status == 200) { 
        var obj = JSON.parse(req.responseText); 
        deadlines = obj 
        for (deadline in deadlines) { 
         var output = ''; 
         for (var property in deadline) { 
          console.log(property) 
          output += property + ': ' + deadline[property] + '; '; 
         } 
         console.log(output); 
         console.log(deadline.date) 
         console.log(deadline.action) 
        } 
       } 
      }; 
     } 
    </script> 

</body> 

然而,當我嘗試列出每個對象的屬性,我得到非常奇怪的結果:

enter image description here

而不是名稱和我正在尋找的價值。有人能告訴我我做錯了什麼嗎?

+1

'deadlines'是一個**數組**。所以它必須由'for'迭代,而不是'for..in' – hindmost

+0

您的JSON沒有跨源頭,因此我無法正確診斷它。另外,使用'deadline.forEach(function(deadline){...})'而不是'for(x in y)'來循環數組。 –

+0

@Liam Gray請求是同域的,因此CORS在這裏不適用。 – hindmost

回答

0

for...in在鍵上循環(因爲它是一個數組:"0","1" ...)。使用for...offorEach或基本for循環。

我建議forEach這樣的:

deadlines.forEach(function(deadline) { 
    // ... 
}); 
2
$.each(JSON.parse(deadlines), function (index, deadline) { 
    var output = ''; 
    for (var property in deadline) { 
     console.log(property) 
     output += property + ': ' + deadline[property] + '; '; 
    } 
    console.log(output); 
    console.log(deadline.date); 
    console.log(deadline.action); 
}); 

你的JSON字符串包含額外的空間。它應該是「行動」而不是「行動」。

+1

http://needsmorejquery.com –

+0

額外的空間是一個很好的電話。這還有一點解決了這個問題。 – Joe