2016-09-19 77 views
0

我需要從json文件中獲取數組,我不知道如何去做。jQuery從json文件中獲取數組

這是我想從獲取數組代碼:

$.getJSON('saveGames/userID' + userID + '_SAVEALPHA.json', function(data) { 
    console.log("Save data from: userID" + userID + "_SAVEALPHA.json: " + data); 
    var testVar = jQuery.parseJSON(data); 
    var pokemonAryTest = testVar[0].pokemon; 
    pokemonAry = [pokemonAryTest]; 
    console.log("loaded players Pokemon: " + pokemonAry); 
    console.log(pokemonAry[0]) 
}); 

我曾試圖改變pokemonAry 1的指數,它返回undefined。當我保持索引相同時,它返回["Pikachu, Charmander"],所以我認爲它的行爲就像是一個字符串。

這裏的以.json:

"[{\"userID\":\"1\",\"saveName\":\"g\",\"pokemon\":[\"Pikachu, Charmander\"]}]" 
+1

您將'pokemonAry'定義爲一個項目的數組。你爲什麼期望它有第二個項目? – SLaks

+1

如果Pikacu和Charmander應該是單獨的數組項目,那麼您需要將JSON設置爲'[\「皮卡丘\」,\「Charmander \」]''。另外,你的'pokemonAryTest'變量應該已經是一個數組了,做'pokemonAry = [pokemonAryTest]'是沒有意義的。 – nnnnnn

回答

0

當您使用getJSON()方法不需要解析JSON數據,jQuery的照顧它。 :)

$.getJSON('saveGames/userID' + userID + '_SAVEALPHA.json', function(data) { 
    console.log("Save data from: userID" + userID + "_SAVEALPHA.json: " + data); 
    var pokemonAry = data[0].pokemon; 
    console.log("loaded players Pokemon: " + pokemonAry); 
    console.log(pokemonAry[0]) 
}); 
+0

那麼現在我得到這個錯誤:加載玩家口袋妖怪:undefined game.js:64未捕獲TypeError:無法讀取未定義的屬性'0'如果你不知道我在做什麼,我設置一個變量到小精靈我在上面發佈的json中的數組 – SeanOMik