0

I've got a Sparql query in javascript format which I want to use in my Vue 2 component, I want to convert the JSON result into an HTML table that I can customize, but I have still not figured out how to go through it. Can anyone help me?

Code :

    class SPARQLQueryDispatcher {
    constructor( endpoint ) {
        this.endpoint = endpoint;
    }

    query( sparqlQuery ) {
        const fullUrl = this.endpoint + '?query=' + encodeURIComponent( sparqlQuery );
        const headers = { 'Accept': 'application/sparql-results+json' };

        return fetch( fullUrl, { headers } ).then( body => body.json() );
    }
}

const endpointUrl = 'https://query.wikidata.org/sparql';
const sparqlQuery = `#Pokémon!
# Updated 2020-06-17

# Gotta catch 'em all
SELECT DISTINCT ?pokemon ?pokemonLabel ?pokedexNumber
WHERE
{
    ?pokemon wdt:P31/wdt:P279* wd:Q3966183 .
    ?pokemon p:P1685 ?statement.
    ?statement ps:P1685 ?pokedexNumber;
              pq:P972 wd:Q20005020.
    FILTER (! wikibase:isSomeValue(?pokedexNumber) )
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
ORDER BY (?pokedexNumber)`;

const queryDispatcher = new SPARQLQueryDispatcher( endpointUrl );
queryDispatcher.query( sparqlQuery ).then( console.log );

1 Answers1

0

SPARQL will always respond with the SPARQL 1.1 Query Results Format: https://www.w3.org/TR/sparql11-results-json

This is a tabular result set, so iterating over the results will give you one 'row' each element in the array, which you can use to populate your HTML table row.

There are many ways to obtain an array of JSON objects and iterate over them, some described here: How do I iterate over a JSON structure? Alternatively, you could use JSONPath to iterate over the results and generate the HTML. A suitable JSONpath could be "$..bindings..*", which will give you an array of each result.

Alternatively to all this, why not look at the available libraries already with capabilities to interact with SPARQL, RDF and result sets. Some listed here: https://www.w3.org/community/rdfjs/wiki/Comparison_of_RDFJS_libraries

Charles
  • 186
  • 1
  • 8