-3
Wenn ich einen Server abfrage, bekomme ich eine JSON-Datei zurück. Die JSON-Datei, die ich zurückbekomme, würde das folgende Format haben.Wie verwende ich JSON-Daten?
{
"head": {
"link": [],
"vars": ["bookName", "author"]
},
"results": {
"distinct": false,
"ordered": true,
"bindings": [
{
"bookName": {
"type": "literal",
"xml:lang": "en",
"value": "Of Mice and Men"
},
"author": {
"type": "literal",
"xml:lang": "en",
"value": "John Steinbeck"
}
}
]
}
}
Dies ist, was ich bisher getan haben:
$.ajax({
dataType: "jsonp",
url: queryUrl,
success: function(data) {
// get the table element
var table = $("#results");
// get the sparql variables from the 'head' of the data.
var headerVars = data.head.vars;
// using the vars, make some table headers and add them to the table;
var trHeaders = getTableHeaders(headerVars);
table.append(trHeaders);
// grab the actual results from the data.
var bindings = data.results.bindings;
var book = data.results.bindings[1].bookName.value;
// for each result, make a table row and add it to the table.
var numberOfBooks = 0;
for(rowIdx in bindings){
table.append(getTableRow(headerVars, bindings[rowIdx]));
numberOfBooks++;
}
document.getElementById("searched-for").innerHTML="<h1>You seach for " + '"' + input + '"' + " and we found " + numberOfBooks + " books </h1>";
}
});
Was so etwas sein, ich möchte in der Lage zu tun:
var book = data.results.binding[1].bookName.value;
Arrays sind nullindiziert, also 'bindings [1]' selektiert das * zweite * Element (und es gibt nur eines). Ist das das Problem? – JJJ
Es ist kein JSON, dies ist Javascript-Objekt. Anstatt 'for in' zu verwenden, verwenden Sie' forEach oder map' Methoden. @JJJ hat recht, du hast das einzige Objekt im Array, also sollte es [0] statt [1] sein –