user3013745
user3013745

Reputation: 59

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?

My 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"}]

Upvotes: 1

Views: 938

Answers (3)

Sebastian G. Marinescu
Sebastian G. Marinescu

Reputation: 2394

Well, a little too late, but since I wrote something, maybe it helps somebody:

$(document).ready(function() {

  var searchResults = [];

  // Assuming data will be something like this
  // data = [{"title":"the book","author":"Peter","ISBN":"632764"},{"title":"the other book","author":"Sebastian","ISBN":"123456"}];

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

    if (typeof data === 'object' && data.length > 0) {

      searchResults = data;
      console.info('Referenced to outside variable');

      for (var amount = 0; amount < searchResults.length; amount++) {
        var result = searchResults[amount];

        // do something with each result here

        console.group('Search-Result:');
        console.log('Title: ', result.title);
        console.log('Author: ', result.author);
        console.log('ISBN: ', result.ISBN);
        console.groupEnd();

      }
    } else {
      console.error('Received wrong data, expecting data to be array');
    }

  });
});

Upvotes: 0

Kld
Kld

Reputation: 7068

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

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

});
});

Upvotes: 1

Jesus Angulo
Jesus Angulo

Reputation: 2666

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"}

Upvotes: 2

Related Questions