Skip to content

Pydantic JSON-LD

pydantic-jsonld is a light-weight Python package that aims to make use of pydantic for JSON-LD data.

What this is not: This package offers no functionality for compaction or expansion. Neither does it parse any given context.

Installation

pip install pydantic-jsonld

Structure

This package offers two BaseModel implementations derived from pydantic. One for working with compacted JSON-LD data and one for expanded JSON-LD data.

Since there is no implementation of context parsing, the compacted model includes several limitations.

This is, however, a design choice as to avoid the necessity of fetching external contexts as well as the heavy computation that comes with validating JSON-LD data.

Usage

For the most basic usage, see the following example

from pydantic_jsonld.compact import BaseModel, Value


# Define a model
class MyModel(BaseModel):
    height: Value[float]
    length: Value[float]


# Build an instance from JSON-LD data
data = {
    "@context": {"@vocab": "http://www.example.org/"},
    "height": 20.0,
    "length": 10.0,
}
model = MyModel.model_validate(data)

# Access via model properties
assert model.height.value == 20.0
assert model.length.value == 10.0

# Recover the original data
dumped = model.model_dump(by_alias=True, exclude_none=True)
assert dumped == data

License

This project is licensed under the MIT License.