Skip to content

Instantly share code, notes, and snippets.

@joernhees
Created November 5, 2010 17:59
Show Gist options
  • Save joernhees/664534 to your computer and use it in GitHub Desktop.
Save joernhees/664534 to your computer and use it in GitHub Desktop.
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 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment