2

Sometimes SPARQL code appears in URLs, as long query strings, and then it is basically a very long one-liner, often URL-encoded. Or the SPARQL contains a lot of UNIONs which have linebreaks located at the wrong places.

I am looking for a SPARQL query formatter.

Ideally, that would be a VSCode extension. However currently (Dec 2020) there exists no such extension in the VSCode marketplace.

I would also work with a command line tool (for Linux), or an online tool where users can paste in the unformatted query and receive a formatted query.

2 Answers 2

2

Answering my own question:

Wikidata has a formatter in the Wikidata Query service. I can copy my unformatted query text, paste it in the Wikidata window, and the query will be formatted.

enter image description here

However the "diamond symbol/icon is only enabled and only works if the query is syntactically valid, and if it has no undefined prefixes.

It does not have to be a query that the Wikidata Service actually understands. (I don't have to execute it with the Wikidata Query Service.).

command-line formatting with wdq

The same Wikidata formatting service can be called with the wdq commandline tool which is available from the debian/ubuntu repos (apt info wdq).

With the --no-execute option, this compact query will be formatted and pretty-printed:

# input / shell command
wdq -tplanet '?planet wdt:P31 wd:Q44559; wdt:P397 ?sun' --no-execute

Output

# --no-execute flag: 
# output / formatted query, with prefixes
PREFIX bd: <http://www.bigdata.com/rdf#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX schema: <http://schema.org/>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX wikibase: <http://wikiba.se/ontology#>
SELECT * WHERE {
    ?planet wdt:P31 wd:Q44559 .
    ?planet wdt:P397 ?sun .
    SERVICE wikibase:label {
        bd:serviceParam wikibase:language "en" .
        ?planet rdfs:label ?planetLabel .
        ?planet schema:description ?planetDescription .
    }
}
1

An excellent javascript library to format SPARQL 1.1 is sparql-formatter

it has a GitHub repository: https://github.com/sparqling/sparql-formatter

And an online playground page: https://sparql-formatter.dbcls.jp/

1
  • Please describe the tool further. Commented Nov 20 at 11:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.