PyLD: A Python JSON-LD Processor
Documentation |
Installation | Usage | Advanced
Topics | What's new in version 4 |
Contributing |
Changelog
Introduction
This library is an implementation of the JSON-LD specification in
Python.
JSON, as specified in RFC7159, is a simple
language for representing objects on the Web. Linked Data is a way of describing
content across different documents or Web sites. Web resources are described
using IRIs, and typically are dereferencable entities that may be used to find
more information, creating a "Web of Knowledge". JSON-LD
is intended to be a simple publishing method for expressing not only Linked Data
in JSON, but for adding semantics to existing JSON.
JSON-LD is designed as a light-weight syntax that can be used to express Linked
Data. It is primarily intended to be a way to express Linked Data in JavaScript
and other Web-based programming environments. It is also useful when building
interoperable Web Services and when storing Linked Data in JSON-based document
storage engines. It is practical and designed to be as simple as possible,
utilizing the large number of JSON parsers and existing code that is in use
today. It is designed to be able to express key-value pairs, RDF data,
RDFa data,
Microformats data, and
Microdata. That is, it supports every major
Web-based structured data model in use today.
The syntax does not require many applications to change their JSON, but easily
add meaning by adding context in a way that is either in-band or out-of-band.
The syntax is designed to not disturb already deployed systems running on JSON,
but provide a smooth migration path from JSON to JSON with added semantics.
Finally, the format is intended to be fast to parse, fast to generate,
stream-based and document-based processing compatible, and require a very small
memory footprint in order to operate.
Requirements
- Python (3.10 or later)
- rdflib (7.3 or later)
- Requests (optional)
- aiohttp (optional)
What's new in version 4
PyLD 4 moves RDF handling to RDFLib and adds
RDF Dataset Canonicalization 1.0 support.
The main developer-facing changes are:
jsonld.to_rdf() returns an rdflib.Dataset by default when no output
format is requested.
jsonld.to_rdf(doc, {'legacyMode': True}) returns the RDF.js-like dataset
dict used by PyLD versions lower than 4.
jsonld.from_rdf() accepts rdflib.Dataset, N-Quads strings, and the legacy
dataset dict.
jsonld.normalize() defaults to RDFC10; pass {'algorithm': 'URDNA2015'}
if older canonicalization output must remain stable.
- The internal
pyld.nquads parser/serializer module has been removed. Use the
JSON-LD APIs with format: 'application/n-quads' or RDFLib directly.
See the full version 4 upgrade notes
and the 4.0.0 changelog entry.
Installation
PyLD can be installed with a pip
package:
pip install PyLD
Defining a dependency on pyld will not pull in
Requests or
aiohttp. If you need one of these for a
Document Loader then either depend on the desired external library directly
or define the requirement as PyLD[requests] or PyLD[aiohttp].
Command line
Install the optional CLI extra to get a JSON-LD 1.1 pyld console script:
pip install "PyLD[cli]"
pyld expand document.jsonld
pyld compact document.jsonld context.jsonld
pyld frame document.jsonld frame.jsonld
pyld to-rdf document.jsonld
pyld from-rdf document.nq
The CLI also provides get, flatten, and HTTP cache management. See the
CLI documentation for all commands,
options, and stdin support.
Usage
Here are some quick examples to get started:
from pyld import jsonld
from pyld.identifier_issuer import IdentifierIssuer
import json
doc = {
"http://schema.org/name": "Manu Sporny",
"http://schema.org/url": {"@id": "http://manu.sporny.org/"},
"http://schema.org/image": {"@id": "http://manu.sporny.org/images/manu.png"}
}
context = {
"name": "http://schema.org/name",
"homepage": {"@id": "http://schema.org/url", "@type": "@id"},
"image": {"@id": "http://schema.org/image", "@type": "@id"}
}
# compact a document according to a particular context
# see: https://json-ld.org/spec/latest/json-ld/#compacted-document-form
compacted = jsonld.compact(doc, context)
print(json.dumps(compacted, indent=2))
# Output:
# {
# "@context": {...},
# "image": "http://manu.sporny.org/images/manu.png",
# "homepage": "http://manu.sporny.org/",
# "name": "Manu Sporny"
# }
# compact using URLs
jsonld.compact('http://example.org/doc', 'http://example.org/context')
# expand a document, removing its context
# see: https://json-ld.org/spec/latest/json-ld/#expanded-document-form
expanded = jsonld.expand(compacted)
print(json.dumps(expanded, indent=2))
# Output:
# [{
# "http://schema.org/image": [{"@id": "http://manu.sporny.org/images/manu.png"}],
# "http://schema.org/name": [{"@value": "Manu Sporny"}],
# "http://schema.org/url": [{"@id": "http://manu.sporny.org/"}]
# }]
# expand using URLs
jsonld.expand('http://example.org/doc')
# flatten a document
# see: https://json-ld.org/spec/latest/json-ld/#flattened-document-form
flattened = jsonld.flatten(doc)
# all deep-level trees flattened to the top-level
# frame a document
# see: https://json-ld.org/spec/latest/json-ld-framing/#introduction
framed = jsonld.frame(doc, frame)
# document transformed into a particular tree structure per the given frame
# normalize a document using RDF Dataset Canonicalization 1.0
# (RDFC10), see: https://www.w3.org/TR/rdf-canon/
normalized = jsonld.normalize(
doc, {'algorithm': 'RDFC10', 'format': 'application/n-quads'})
# normalized is a string that is a canonical representation of the document
# that can be used for hashing, comparison, etc.
# convert a document to RDF with a custom blank node issuer
issuer = IdentifierIssuer('_:doc')
rdf = jsonld.to_rdf(
doc,
{'identifierIssuer': issuer, 'format': 'application/n-quads'})
# flatten() and frame() accept the same identifierIssuer option
jsonld.to_rdf() returns an rdflib.Dataset when no output format is
requested. To keep the RDF.js-like dataset dict used by PyLD versions lower
than 4, pass
{'legacyMode': True}:
dataset = jsonld.to_rdf(doc, {'legacyMode': True})
Features & conformance
This library aims to conform with the following W3C Recommendations:
The test runner is
often updated to note or skip newer tests that are not yet supported.
Advanced Topics
Document Loader
The default document loader for PyLD uses
Requests. In a production environment you
may want to setup a custom loader that, at a minimum, sets a timeout value. You
can also force requests to use https, set client certs, disable verification, or
set other Requests parameters.
jsonld.set_document_loader(jsonld.requests_document_loader(timeout=...))
The factory remains the compatibility API, and the concrete class is also
available when class-based construction is preferred:
from pyld import RequestsDocumentLoader
jsonld.set_document_loader(RequestsDocumentLoader(timeout=...))
An asynchronous document loader using aiohttp is also available. Please note
that this document loader limits asynchronicity to fetching documents only. The
processing loops remain synchronous.
jsonld.set_document_loader(jsonld.aiohttp_document_loader(timeout=...))
The concrete aiohttp loader class is available from pyld as well:
from pyld import AioHttpDocumentLoader
jsonld.set_document_loader(AioHttpDocumentLoader(timeout=...))
When no document loader is specified, the default loader is set to
Requests. If Requests is not available, the
loader is set to aiohttp. The fallback document loader is a dummy document
loader that raises an exception on every invocation.
Frozen Document Loader
For air-gapped runs, reproducible builds, and security-hardened deployments that
must not perform any remote context fetches at all, PyLD ships
FrozenDocumentLoader: a class-based loader that serves only the URLs in its
documents allowlist and refuses everything else with
JsonLdError(code='loading document failed').
Instantiating with no arguments serves the curated BUNDLED_CONTEXTS set
(ActivityStreams, DID v1, Verifiable Credentials v1 and v2, Linked Data Security
v1/v2, Ed25519-2020, and JWS-2020). To extend the bundle with additional
pre-vetted contexts, pass a merged mapping:
from pyld import jsonld, FrozenDocumentLoader, BUNDLED_CONTEXTS
loader = FrozenDocumentLoader(documents=dict(
BUNDLED_CONTEXTS,
**{'https://example.com/my-ctx': Path('contexts/my-ctx.jsonld')},
))
jsonld.expand(doc, options={'documentLoader': loader})
This honors the W3C JSON-LD Best Practices recommendation that clients SHOULD
attempt to use a locally cached version of contexts (see
§ Cache JSON-LD Contexts).
Refresh the bundled copies with make download-bundled-contexts.
Customizing the ContextResolver
You can customize the way contexts are loaded and cached by passing an instance
of ContextResolver. The following example implements a loader with a prefilled
custom document cache and uses a custom LRU cache for resolved contexts:
from pyld.jsonld import compact, expand, set_document_loader, ContextResolver
import json
from cachetools import LRUCache
# Load the Linked Art context from file-system
fh = open('linked-art.json')
js = json.load(fh)
fh.close()
# Add to document cache
docCache = {
"https://linked.art/ns/v1/linked-art.json": {
"contextUrl": None,
"documentUrl": "https://linked.art/ns/v1/linked-art.json",
"document": js
}
}
# Custom loader that uses the document cache
def load_document_and_cache(url, options={}):
if url in docCache:
return docCache[url]
doc = {"contextUrl": None, "documentUrl": url, "document": ""}
resp = requests.get(url)
doc["document"] = resp.json()
docCache[url] = doc
return doc
# Set the custom loader as global document loader
set_document_loader(load_document_and_cache)
# Create custom context resolver with custom LRU cache and custom loader
resolved_context_cache = LRUCache(maxsize=1000)
resolver = ContextResolver(resolved_context_cache, load_document_and_cache)
# Expand JSON-LD document using custom context resolver
input = {"@context":"https://linked.art/ns/v1/linked-art.json", "id": "tag:foo", "type": "Person"}
output = expand(input, options={'contextResolver': resolver})
It is also possible to change the maximum number of times that the loader
recursively fetches contexts, by passing the max_context_urls parameter:
resolver = ContextResolver(resolved_context_cache, load_document_and_cache, max_context_urls=20)
# Or you can do...
# resolver = ContextResolver(resolved_context_cache, load_document_and_cache)
# resolver.max_context_urls = 20
output = expand(input, options={'contextResolver': resolver})
Handling ignored properties during JSON-LD expansion
If a property in a JSON-LD document does not map to an absolute IRI then it is
ignored. You can customize this behaviour by passing a customizable handler to
on_property_dropped parameter of jsonld.expand().
For example, you can introduce a strict mode by raising a ValueError on every
dropped property:
def raise_this(value):
raise ValueError(value)
jsonld.expand(doc, None, on_property_dropped=raise_this)
Contributing