2016-05-30 10 views
1

Ich versuche, die Werte "Titel, Autor und ISBN" aus einer JSON-Datei zu analysieren und in einem Array namens availableTags zu speichern, aber ich bekomme nur die Werte undefined und ich weiß nicht wo das Problem ist. Irgendwelche Vorschläge?getJSON() bekommen undefinierte Werte

Mein 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]); 

}); 
}); 

hier ist die JSON-Code

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

'data' ein Array ist. Probiere 'data = data [0]' – Phil

+0

Wird es auch mehrere Sucheinträge geben? Und was willst du am Ende damit erreichen? Was ist dein Ziel'? –

Antwort

2

Sie müssen feststellen, dass Ihre Datenvariable tatsächlich ein Array ist.

Sie müssen Ihren Code ändern:

$(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]); 

}); 
}); 

Sie wahrscheinlich die surronding Klammern verpasst haben.

Dies ist ein Array mit einem Element.

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

Dies ist ein Element.

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

danke das hat funktioniert :) – user3013745

1
$(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]); 

}); 
}); 
0

Nun, ein wenig zu spät, aber da ich etwas geschrieben habe, vielleicht hilft es jemand:

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

    }); 
});