Inject a JSON-LD @context¶
JSON-LD property names only become RDF terms when a context maps them to IRIs.
If the input JSON has no @context, and the source cannot provide one through
an HTTP Link header, pass the context with expandContext.
Use this for JSON already loaded from a file, queue, database, or API client:
- Load or receive the plain JSON document.
- Define the context your application wants to apply.
- Pass that context in the operation
optionsasexpandContext. - Run
jsonld.expand()or another API that expands internally.
PyLD processes expandContext before expansion. If the document also has its
own @context, that document context is processed later and can refine or
override term definitions for the document body.
Example inject_context.py
import json
from pyld import jsonld
doc = {
"name": "Ada Lovelace",
"homepage": "https://example.com/ada",
}
context = {
"name": "http://schema.org/name",
"homepage": {"@id": "http://schema.org/url", "@type": "@id"},
}
expanded = jsonld.expand(doc, {"expandContext": context})
print(json.dumps(expanded, indent=2))
The same option works with APIs that expand internally, including
jsonld.compact(), jsonld.flatten(), and jsonld.frame():
Example inject_context_compact.py
import json
from pyld import jsonld
doc = {
"name": "Ada Lovelace",
"homepage": "https://example.com/ada",
}
source_context = {
"name": "http://schema.org/name",
"homepage": {"@id": "http://schema.org/url", "@type": "@id"},
}
output_context = {
"name": "http://schema.org/name",
"url": {"@id": "http://schema.org/url", "@type": "@id"},
}
compacted = jsonld.compact(
doc,
output_context,
{"expandContext": source_context},
)
print(json.dumps(compacted, indent=2))
Use an in-document @context when you control the JSON. Use expandContext
when the context is application policy or transport metadata.