-3
當我查詢服務器時,我得到一個JSON文件作爲回報。我得到的JSON文件將採用以下格式。如何使用JSON數據?
{
"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"
}
}
]
}
}
這是我迄今所做的:
$.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>";
}
});
我希望能夠做的是這樣的:
var book = data.results.binding[1].bookName.value;
數組是零索引的,所以'bindings [1]'選擇* second *元素(並且只有一個)。這是問題嗎? – JJJ
這不是JSON,這是javascript對象。而不是使用'for in'嘗試使用'forEach或map'方法。 @JJJ是正確的,你在數組中只有一個對象,所以它應該是[0]而不是[1] –