2016-09-19 78 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