SeanOMik SeanOMik - 2 months ago 7
jQuery Question

jQuery undefined returned from json file

I'm trying to get a array from a json but when I try to get that data it returns 'undefined'

Here's where I'm trying to get the data:

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


The json file (generated by PHP)

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


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).

Answer

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

Or you can remove the brackets from the JSON file if that's possible:

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

Comments