0
# Core JSON-LD Processing
1
2
Primary JSON-LD transformation operations that form the foundation of document processing. These functions implement the core JSON-LD algorithms defined in the W3C JSON-LD specification.
3
4
## Capabilities
5
6
### Document Compaction
7
8
Compacts a JSON-LD document according to a given context, producing a more concise representation that uses context-defined terms instead of full IRIs.
9
10
```python { .api }
11
def compact(input_, ctx, options=None):
12
"""
13
Performs JSON-LD compaction.
14
15
Args:
16
input_: The JSON-LD document to compact (dict, list, or str)
17
ctx: The JSON-LD context to compact with (dict or str)
18
options: Optional compaction settings (dict)
19
20
Options:
21
base (str): The base IRI to use
22
compactArrays (bool): True to compact arrays to single values when
23
appropriate (default: True)
24
graph (bool): True to always output a top-level graph (default: False)
25
skipExpansion (bool): True to skip expansion during compaction
26
documentLoader (function): Custom document loader function
27
expandContext (dict): Context to use during expansion
28
processingMode (str): JSON-LD processing mode
29
30
Returns:
31
dict: The compacted JSON-LD document
32
33
Raises:
34
JsonLdError: If compaction fails due to invalid input or context
35
"""
36
```
37
38
#### Example
39
40
```python
41
from pyld import jsonld
42
43
doc = {
44
"http://schema.org/name": "Jane Doe",
45
"http://schema.org/jobTitle": "Software Engineer"
46
}
47
48
context = {
49
"name": "http://schema.org/name",
50
"jobTitle": "http://schema.org/jobTitle"
51
}
52
53
compacted = jsonld.compact(doc, context)
54
# Result: {"@context": {...}, "name": "Jane Doe", "jobTitle": "Software Engineer"}
55
```
56
57
### Document Expansion
58
59
Expands a JSON-LD document by removing context and representing all terms as full IRIs, producing the canonical expanded form.
60
61
```python { .api }
62
def expand(input_, options=None):
63
"""
64
Performs JSON-LD expansion.
65
66
Args:
67
input_: The JSON-LD document to expand (dict, list, or str)
68
options: Optional expansion settings (dict)
69
70
Options:
71
base (str): The base IRI to use
72
expandContext (dict): Context to use during expansion
73
extractAllScripts (bool): True to extract all JSON-LD script elements
74
from HTML (default: False)
75
documentLoader (function): Custom document loader function
76
processingMode (str): JSON-LD processing mode
77
78
Returns:
79
list: The expanded JSON-LD document as an array
80
81
Raises:
82
JsonLdError: If expansion fails due to invalid input
83
"""
84
```
85
86
#### Example
87
88
```python
89
from pyld import jsonld
90
91
doc = {
92
"@context": {"name": "http://schema.org/name"},
93
"name": "John Smith"
94
}
95
96
expanded = jsonld.expand(doc)
97
# Result: [{"http://schema.org/name": [{"@value": "John Smith"}]}]
98
```
99
100
### Document Flattening
101
102
Flattens a JSON-LD document by moving all nested objects to the top level and using node references, optionally applying a context.
103
104
```python { .api }
105
def flatten(input_, ctx=None, options=None):
106
"""
107
Performs JSON-LD flattening.
108
109
Args:
110
input_: The JSON-LD document to flatten (dict, list, or str)
111
ctx: Optional context to apply to flattened document (dict or str)
112
options: Optional flattening settings (dict)
113
114
Options:
115
base (str): The base IRI to use
116
expandContext (dict): Context to use during expansion
117
extractAllScripts (bool): True to extract all JSON-LD script elements
118
from HTML (default: False)
119
documentLoader (function): Custom document loader function
120
processingMode (str): JSON-LD processing mode
121
122
Returns:
123
dict: The flattened JSON-LD document
124
125
Raises:
126
JsonLdError: If flattening fails due to invalid input
127
"""
128
```
129
130
#### Example
131
132
```python
133
from pyld import jsonld
134
135
doc = {
136
"@context": {"name": "http://schema.org/name"},
137
"name": "Alice",
138
"knows": {
139
"name": "Bob"
140
}
141
}
142
143
flattened = jsonld.flatten(doc)
144
# Result: Flat structure with separate nodes and @id references
145
```
146
147
### Document Framing
148
149
Frames a JSON-LD document according to a given frame, reshaping the data into a specific tree structure.
150
151
```python { .api }
152
def frame(input_, frame, options=None):
153
"""
154
Performs JSON-LD framing.
155
156
Args:
157
input_: The JSON-LD document to frame (dict, list, or str)
158
frame: The JSON-LD frame template (dict)
159
options: Optional framing settings (dict)
160
161
Options:
162
base (str): The base IRI to use
163
expandContext (dict): Context to use during expansion
164
extractAllScripts (bool): True to extract all JSON-LD script elements
165
from HTML (default: False)
166
documentLoader (function): Custom document loader function
167
embed (str): How to embed matched objects ('@always', '@once', '@never')
168
explicit (bool): True to only include explicitly framed properties
169
omitDefault (bool): True to omit default values
170
pruneBlankNodeIdentifiers (bool): True to prune blank node identifiers
171
requireAll (bool): True to require all frame properties to match
172
173
Returns:
174
dict: The framed JSON-LD document
175
176
Raises:
177
JsonLdError: If framing fails due to invalid input or frame
178
"""
179
```
180
181
#### Example
182
183
```python
184
from pyld import jsonld
185
186
doc = [
187
{"@id": "http://example.org/person/1", "@type": "Person", "name": "Alice"},
188
{"@id": "http://example.org/person/2", "@type": "Person", "name": "Bob"}
189
]
190
191
frame = {
192
"@context": {"name": "http://schema.org/name"},
193
"@type": "Person",
194
"name": {}
195
}
196
197
framed = jsonld.frame(doc, frame)
198
# Result: Document reshaped according to frame structure
199
```
200
201
### Document Normalization
202
203
Normalizes a JSON-LD document using RDF Dataset Normalization algorithms, producing a canonical string representation suitable for hashing and comparison.
204
205
```python { .api }
206
def normalize(input_, options=None):
207
"""
208
Performs RDF dataset normalization on JSON-LD input.
209
210
Args:
211
input_: The JSON-LD document to normalize (dict, list, or str)
212
options: Optional normalization settings (dict)
213
214
Options:
215
algorithm (str): Normalization algorithm ('URDNA2015' or 'URGNA2012',
216
default: 'URGNA2012')
217
base (str): The base IRI to use
218
expandContext (dict): Context to use during expansion
219
format (str): Output format ('application/n-quads' for string output)
220
inputFormat (str): Input format if not JSON-LD
221
documentLoader (function): Custom document loader function
222
223
Returns:
224
str or dict: Normalized representation (string if format specified,
225
otherwise RDF dataset dict)
226
227
Raises:
228
JsonLdError: If normalization fails due to invalid input
229
"""
230
```
231
232
#### Example
233
234
```python
235
from pyld import jsonld
236
237
doc = {
238
"@context": {"name": "http://schema.org/name"},
239
"name": "Charlie"
240
}
241
242
normalized = jsonld.normalize(doc, {
243
'algorithm': 'URDNA2015',
244
'format': 'application/n-quads'
245
})
246
# Result: Canonical N-Quads string representation
247
```
248
249
### Link Creation
250
251
**EXPERIMENTAL**: Creates a linked data structure by connecting related objects through their identifiers in memory.
252
253
```python { .api }
254
def link(input_, ctx=None, options=None):
255
"""
256
Links a JSON-LD document's nodes in memory (EXPERIMENTAL).
257
258
This experimental function creates bidirectional links between JSON-LD
259
objects that reference each other, enabling in-memory graph traversal.
260
261
Args:
262
input_: The JSON-LD document to link (dict, list, or str)
263
ctx: Optional context to apply during linking (dict or str)
264
options: Optional linking settings (dict)
265
266
Options:
267
base (str): The base IRI to use
268
expandContext (dict): Context to use during expansion
269
270
Returns:
271
dict: The linked JSON-LD document with bidirectional references
272
273
Raises:
274
JsonLdError: If linking fails due to invalid input
275
276
Note:
277
This is an experimental feature and may change in future versions.
278
"""
279
```
280
281
## Processing Options
282
283
### Common Options
284
285
Most processing functions accept these common options:
286
287
- **base** (str): Base IRI for resolving relative IRIs
288
- **documentLoader** (function): Custom function for loading remote documents
289
- **expandContext** (dict): Additional context to use during expansion
290
- **processingMode** (str): JSON-LD processing mode ('json-ld-1.0' or 'json-ld-1.1')
291
292
### Compaction-Specific Options
293
294
- **compactArrays** (bool): Whether to compact single-item arrays to single values
295
- **graph** (bool): Whether to always output a top-level @graph
296
- **skipExpansion** (bool): Whether to skip the expansion step during compaction
297
298
### Framing-Specific Options
299
300
- **embed** (str): Embedding mode ('@always', '@once', '@never')
301
- **explicit** (bool): Whether to include only explicitly framed properties
302
- **omitDefault** (bool): Whether to omit properties with default values
303
- **requireAll** (bool): Whether all frame properties must match
304
305
### Normalization-Specific Options
306
307
- **algorithm** (str): Normalization algorithm ('URDNA2015' recommended)
308
- **format** (str): Output format ('application/n-quads' for string output)
309
- **inputFormat** (str): Input format if not JSON-LD
310
311
## Error Handling
312
313
All processing functions may raise `JsonLdError` exceptions with specific error types:
314
315
- **loading document failed**: Document loading errors
316
- **invalid @context**: Context processing errors
317
- **compaction error**: Compaction-specific errors
318
- **expansion error**: Expansion-specific errors
319
- **framing error**: Framing-specific errors
320
- **normalization error**: Normalization-specific errors