Skip to content

yaml_ld.compact.compact

compact(
    document: JsonLdInput,
    ctx: JsonLdContext | None = None,
    options: CompactOptions = DEFAULT_COMPACT_OPTIONS,
) -> JsonLdRecord | list[JsonLdRecord]

Compact a *-LD document.

Replace full IRIs with shorter terms and compact IRIs using a context, making the document more human-readable while preserving its original structure and semantics.

Example

compact.py
import yaml

import yaml_ld

print(
    yaml.dump(
        yaml_ld.compact(
            'pythagorean-theorem.yamlld',
            ctx='ctx.jsonld',
        ),
    ),
)
ctx.jsonld
{
  "@context": {
    "dbp": "https://dbpedia.org/page/"
  }
}
pythagorean-theorem.yamlld
"@context":
  - https://json-ld.org/contexts/dollar-convenience.jsonld
  - prov: http://www.w3.org/ns/prov#
  - variable: https://variables.namespace/
    =: https://math.namespace/equal
    +: https://math.namespace/add
    ²: https://math.namespace/squared

$id: https://dbpedia.org/page/Pythagorean_theorem
prov:Entity:
  =:
    - +:
      - ²: variable:a
      - ²: variable:b
    - ²: variable:c
python compact.py
'@context': ctx.jsonld
'@id': dbp:Pythagorean_theorem
http://www.w3.org/ns/prov#Entity:
  https://math.namespace/equal:
  - https://math.namespace/add:
    - https://math.namespace/squared: variable:a
    - https://math.namespace/squared: variable:b
  - https://math.namespace/squared: variable:c