public
Last active

converts a result's bindings to their corresponding rdflib terms, e.g. URIref, Literal, BNode

  • Download Gist
sparqlwrapperResToRDFlib.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
# -*- coding: utf-8 -*-
'''
Created on Oct 30, 2010
 
@author: joern
'''
import rdflib
 
def sparqlJSONresultBindingsToRDFlib(resBindings):
""" Converts a result's bindings as retrieved in res["results"]["bindings"]
by SPARQLWrapper with a sparql select query into the corresponding
list with rdflib terms, e.g., Literal, URIref, BNode.
BNodes won't be mixed between iterated calls of this function even if
they happen to have the same "value". Internally the given value is mapped
to a random value, which is remembered in _one and the same_ call of this
function only."""
_bnodes = {} # makes sure we don't confuse BNodes from different results
def dictToRDFlib(d):
""" Maps a dict following the syntax in http://www.w3.org/TR/rdf-sparql-json-res/
to the corresponding rdflib term. """
if d == None: return None
t = d["type"]
v = d["value"]
if t == "uri":
return rdflib.URIRef(v)
if t == "bnode":
if v not in _bnodes:
_bnodes[v] = rdflib.BNode() # v is not used as BNode value on purpose (multiple calls should not have the same value)
return _bnodes[v]
l = d.get("xml:lang", None)
if t == "literal":
return rdflib.Literal(v, lang=l)
if t == "typed-literal":
return rdflib.Literal(v, lang=l, datatype=d["datatype"]) # will raise type error if lang and datatype set
raise rdflib.exceptions.ParserError(
"Invalid sparql json result according to http://www.w3.org/TR/rdf-sparql-json-res/: {0}".format(d))
resBindingsRDFlib = []
for row in resBindings:
tmp = {}
for k,v in row.items():
tmp[k] = dictToRDFlib(v)
resBindingsRDFlib.append(tmp)
return resBindingsRDFlib

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.