RDFLib and jsonld¶
Use this pattern when JSON-LD is your interchange format, but RDF tooling is the best place to query, update, serialize, or store the graph.
Install PyLD:
PyLD 4 installs and uses RDFLib for RDF datasets. The processing order is:
- Start with JSON-LD that has a usable
@context. - Convert it with
jsonld.to_rdf(). - Process the returned
rdflib.Datasetwith RDFLib. - Convert it back with
jsonld.from_rdf()if the next layer expects JSON-LD. - Compact the result with
jsonld.compact()if developers or APIs should see terms such asnameinstead of full IRIs.
Example rdflib_processing.py
import json
from rdflib import Namespace, URIRef
from pyld import jsonld
SCHEMA = Namespace("http://schema.org/")
subject = URIRef("http://dbpedia.org/resource/Earth")
doc = {
"@context": {"name": str(SCHEMA.name)},
"@id": str(subject),
"name": "Earth",
}
dataset = jsonld.to_rdf(doc)
dataset.add((subject, SCHEMA.url, URIRef("https://example.com/earth")))
jsonld_doc = jsonld.from_rdf(dataset)
compacted = jsonld.compact(
jsonld_doc,
{
"name": str(SCHEMA.name),
"homepage": {"@id": str(SCHEMA.url), "@type": "@id"},
},
)
print(json.dumps(compacted, indent=2))
For simple lookups, use RDFLib's graph methods on the dataset returned by
jsonld.to_rdf():
Example rdflib_query.py
import json
from rdflib import Namespace, URIRef
from pyld import jsonld
SCHEMA = Namespace("http://schema.org/")
subject = URIRef("http://dbpedia.org/resource/Earth")
doc = {
"@context": {"name": str(SCHEMA.name)},
"@id": str(subject),
"name": "Earth",
}
dataset = jsonld.to_rdf(doc)
names = [str(value) for value in dataset.objects(subject, SCHEMA.name)]
print(json.dumps(names, indent=2))
For RDF that starts outside PyLD, parse it with RDFLib first, then pass the
rdflib.Dataset to jsonld.from_rdf():
Example rdflib_parse.py
import json
from rdflib import Dataset
from pyld import jsonld
nquads = (
'<http://dbpedia.org/resource/Earth> '
'<http://schema.org/name> "Earth" .\n'
)
dataset = Dataset().parse(data=nquads, format="nquads")
doc = jsonld.from_rdf(dataset)
compacted = jsonld.compact(doc, {"name": "http://schema.org/name"})
print(json.dumps(compacted, indent=2))
Use format only when you need a serialized RDF string instead of an in-memory
rdflib.Dataset:
Use jsonld.from_rdf(dataset) directly when you already have an
rdflib.Dataset from another RDFLib parser, store, or query result.