Reputation: 59
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
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
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
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