Skip to content

Instantly share code, notes, and snippets.

@EpicKiwi
Last active September 29, 2022 09:17
Show Gist options
  • Save EpicKiwi/ba0cb9af9527678a6129e4ddee6d6e21 to your computer and use it in GitHub Desktop.
Save EpicKiwi/ba0cb9af9527678a6129e4ddee6d6e21 to your computer and use it in GitHub Desktop.
A simple 4 lines script to convert JSON-exported `CONSTRUCT` queries from WIKIDATA into Turtle (ttl) file

Wikidata Query to Turtle Conversion

A simple 4 lines script to convert JSON-exported CONSTRUCT queries from WIKIDATA into Turtle (ttl) file

How to use

Build a CONSTRUCT query into Wikidata Query Service and export the result in JSON using the "Download button"

For exemple this query exporting Game Of Thrones Characters

PREFIX schema: <http://schema.org/>

CONSTRUCT {
  ?c a schema:Person .
  ?c schema:name ?cLabel .
  ?c schema:parent ?cm .
  ?c schema:parent ?cf .
  ?c schema:sibling ?cs .
  ?c schema:affiliation ?cfa .
  ?c schema:gender ?cgenderLabel .
  ?c schema:birthPlace ?cbirthPlaceLabel .
  # ?c schema:deathPlace ?cdeathPlaceLabel . SPOILERS
  ?c schema:spouse ?cspouse .
  
  ?cfa a schema:Organization .
  ?cfa schema:name ?cfaLabel .
 }
WHERE {
  
  ?c wdt:P31 wd:Q20086263 .
  ?c wdt:P1080 wd:Q2461698 .
  
  OPTIONAL { ?c wdt:P25 ?cm . ?cm wdt:P1080 wd:Q2461698 . } # Mother
  OPTIONAL { ?c wdt:P21 ?cgender} # Gender
  OPTIONAL { ?c wdt:P19 ?cbirthPlace} # Birthplace
  OPTIONAL { ?c wdt:P20 ?cdeathPlace} # DeathPlace
  OPTIONAL { ?c wdt:P22 ?cf . ?cf wdt:P1080 wd:Q2461698 .  } # Father
  OPTIONAL { ?c wdt:P3373 ?cs . ?cs wdt:P1080 wd:Q2461698 .  } # Sibling
  OPTIONAL { ?c wdt:P26 ?cspouse . ?cspouse wdt:P1080 wd:Q2461698 .  } # Spouse
  OPTIONAL { ?c wdt:P53 ?cfa . ?cfa wdt:P1080 wd:Q2461698 .  } # family
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  
}

Edit the 2 first lines and set your downloaded file path in SOURCE and the target turtle file in DESTINATION.

Paste the 4 lines into your shell and run it

DESTINATION="query.ttl"; \
SOURCE="query(3).json"; \
cat "$SOURCE" | jq '.[] | select(.object | startswith("http") ) | "<" + (.subject) + "> <" + (.predicate) + "> <" + (.object) + "> ."' -r > "$DESTINATION"; \
cat "$SOURCE" | jq '.[] | select(.object | startswith("http") | not) | "<" + (.subject) + "> <" + (.predicate) + "> \"" + (.object) + "\" ."' -r >> "$DESTINATION"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment