Skip to content

Open a JSON-LD file

For a local .jsonld file that already contains its @context, use Python's standard json module first. PyLD processes Python objects, so the usual order is:

pip install PyLD
  1. Read the file with pathlib.Path.
  2. Parse it with json.loads() or json.load().
  3. Pass the parsed object to jsonld.expand(), jsonld.compact(), jsonld.to_rdf(), or another PyLD API.

Example open_jsonld_file.py

import json
from pathlib import Path

from pyld import jsonld

path = Path(__file__).resolve().parent / "data" / "person.jsonld"
doc = json.loads(path.read_text())

expanded = jsonld.expand(doc)

print(json.dumps(expanded, indent=2))
Output
[
  {
    "http://schema.org/name": [
      {
        "@value": "Ada Lovelace"
      }
    ]
  }
]

After parsing the file, use any PyLD operation. For example, convert the local JSON-LD file to N-Quads:

Example open_jsonld_file_to_rdf.py

import json
from pathlib import Path

from pyld import jsonld

path = Path(__file__).resolve().parent / "data" / "person.jsonld"
doc = json.loads(path.read_text())

nquads = jsonld.to_rdf(doc, {"format": "application/n-quads"})

print(nquads)
Output
_:b0 <http://schema.org/name> "Ada Lovelace"^^<http://www.w3.org/2001/XMLSchema#string>  .

That is enough for local files with inline contexts. Choose a document loader only when PyLD must dereference a URL during processing.

If the document uses remote contexts, install and pass RequestsDocumentLoader:

pip install "PyLD[requests]"

If PyLD should load the JSON-LD document itself from a file: URL, use FileDocumentLoader and pass it with documentLoader in the operation options. Direct json.load() is simpler when you already know the file path and only need to process that one file.