Ieuan Walker Ieuan Walker - 1 month ago 16
JSON Question

How do I use JSON data?

When I query a server I get a JSON file in return. The JSON file I get back would be in the following format.

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


This is what I have done so far:

$.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>";
}
});


What I want to be able to do is something like this:

var book = data.results.binding[1].bookName.value;

Answer

Try this:

$.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;

    if(bindings && bindings.length) {
        book = bindings[0].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>";
}
}); 

But that will only get the first book, if it exists.