user3013745 user3013745 - 6 months ago 26
jQuery Question

getJSON() getting undefined values

I´m trying to parse the values "title,author and ISBN" from a JSON file and store them in an array called availableTags but i get only the values undefined and i don´t know where the problem is.
Any suggestions?

code

$(document).ready(function () {
var availableTags = [];

$.getJSON( "search.json", function( data ) {

availableTags[0] = data.title;
availableTags[1] = data.author;
availableTags[2] = data.ISBN;
alert(availableTags[0]);

});
});


here is the JSON code

[{"title":"the book","author":"Peter","ISBN":"632764"}]

Answer

You need to notice that your data variable is actually an array.

You need to change your code to:

$(document).ready(function () {
    var availableTags = [];

  $.getJSON( "search.json", function( data ) {
    data = data[0];
    availableTags[0] = data.title;
    availableTags[1] = data.author;
    availableTags[2] = data.ISBN;
    alert(availableTags[0]);

});
});

You probably have missed the surronding brackets.

This is an array with one item.

[{"title":"the book","author":"Peter","ISBN":"632764"}]

This is one item.

{"title":"the book","author":"Peter","ISBN":"632764"}
Comments