2017-05-04 34 views
1

這解析JSON文件是我使用JSON:json試圖從URL

我希望能拉不同的數據出來,並在網頁上顯示它。特別是徽章的名稱和相關信息。徽章陣列給我帶來麻煩。

我看過這裏的jQuery文檔:http://api.jquery.com/jquery.getjson/ 但他們有點失去我,因爲它不符合我想要做的。

這裏是js文件我沒有運氣嘗試...謝謝

`

//Function to print message to console 
function printMessage(badgeCount, points, arr) { 
    const message = `Anthony Scott has ${badgeCount} total badge(s) and ${points} points in JavaScript. here is a list of badges ${arr}`; 

    document.write(message); 
} 

(function() { 
    $.getJSON("https://teamtreehouse.com/anthonyscott4.json", {}) 
    .done(function(data) { 
      // Parse the data 
       const profile = JSON.parse(data);        
       // Print the data 
           let arr = []; 
           for(var x in profile.badges) { 
            arr.push(profile.badges[x].name) 
           } 
       document.write(profile.badges.length, profile.points.JavaScript, arr); 
    }); 

}); 

`

+0

你的數據已經是一個對象。無需解析它。 JavaScript解釋器已經爲你解析了它。 https://jsfiddle.net/sumitridhal/bapxdenw/ –

+0

使用'jQuery.parseJSON解析(JSON.stringify(data));' –

回答

0

由於您使用$.getJSONJSON在回調已經被解析爲您,所以不需要在結果上調用JSON.parse

for in循環用於iterate over an objects properties。你所尋找的是一個正常for環或forEach

var request = $.getJSON('https://teamtreehouse.com/anthonyscott4.json'); 
 
request.done(function (response) { 
 
    var badges = []; 
 
    response.badges.forEach(function (badge) { 
 
    badges.push(badge.name); 
 
    }); 
 
    $('#result').append(badges.toString()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="result"></div>

例與for循環:

var request = $.getJSON('https://teamtreehouse.com/anthonyscott4.json'); 
 
request.done(function (response) { 
 
    var badges = []; 
 
    for (var i = 0; i < response.badges.length; ++i) { 
 
    var badge = response.badges[i]; 
 
    badges.push(badge.name); 
 
    } 
 
    $('#result').append(badges.toString()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="result"></div>