Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
converts a result's bindings to their corresponding rdflib terms, e.g. URIref, Literal, BNode
# -*- 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
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 {0}".format(d))
resBindingsRDFlib = []
for row in resBindings:
tmp = {}
for k,v in row.items():
tmp[k] = dictToRDFlib(v)
return resBindingsRDFlib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.