简体   繁体   English

jQuery从json文件获取数组

[英]jQuery get an Array from json file

I need to get an array from a json file and I have no idea how to do it. 我需要从json文件中获取数组,但我不知道该怎么做。

Here's the code I want to get the array from: 这是我要从中获取数组的代码:

$.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])
});

I have tried to change the index of pokemonAry to 1 and it returns undefined. 我试图将pokemonAry的索引pokemonAry为1,并且它返回undefined。 And when I keep the index the same, it returns ["Pikachu, Charmander"] so I think its acting like as if it's a string. 当我保持索引不变时,它返回["Pikachu, Charmander"]因此我认为它的行为就像是一个字符串。

Here's the .json: 这是.json:

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

When you are using getJSON() method no need to parse JSON data, jQuery take care of it. 当您使用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])
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM