从json文件返回的jQuery undefined [英] jQuery undefined returned from json file
问题描述
我正在尝试从json获取数组,但是当我尝试获取该数据时,它返回未定义"
I'm trying to get a array from a json but when I try to get that data it returns 'undefined'
在这里我要获取数据:
$.getJSON('saveGames/userID' + userID + '_SAVEALPHA.json', function(data) {
console.log("Got data from saveJSON: " + data);
var testVar = jQuery.parseJSON(data);
console.log(testVar);
playersPokemon = testVar.pokemon;
console.log(testVar.pokemon);
console.log("Players Pokemon: " + playersPokemon);
});
json文件(由PHP生成)
The json file (generated by PHP)
"[{\"userID\":\"1\",\"saveName\":\"h\",\"pokemon\":[\"Pikachu\",\"Charmander\"]}]"
我已经使用json验证程序来检查此文件,没关系.我正在尝试使用jQuery访问此json文件(以防您不知道).
I have used a json validator to check this file and it was OK. I am trying to access this json file with jQuery (in case you didn't know).
推荐答案
您的JSON字符串是对象的数组:[{...}]
,pokemon
属性在对象而不是数组中,因此要访问它,您需要testVar[0].pokemon
Your JSON string is an Array of an Object: [{...}]
, the pokemon
property is in the Object not the Array so to access it you need testVar[0].pokemon
或者,如果可能的话,您可以从JSON文件中删除括号:
Or you can remove the brackets from the JSON file if that's possible:
"{\"userID\":\"1\",\"saveName\":\"h\",\"pokemon\":[\"Pikachu\",\"Charmander\"]}"
这篇关于从json文件返回的jQuery undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!