0
# Utility Operations
1
2
Comprehensive utility functions for JSON-LD data manipulation, node mapping, and experimental features. These utilities provide lower-level operations and specialized functionality for advanced JSON-LD processing scenarios.
3
4
## Capabilities
5
6
### Create Node Map
7
8
Creates a merged node map from JSON-LD input, flattening all nodes into a single map indexed by node ID.
9
10
```javascript { .api }
11
/**
12
* Creates a merged node map from JSON-LD input
13
* @param input - The JSON-LD input
14
* @param options - Optional configuration object
15
* @returns Promise resolving to merged node map
16
*/
17
function createNodeMap(input, options);
18
```
19
20
**Parameters:**
21
- `input` (any): JSON-LD input to process
22
- `options` (NodeMapOptions, optional): Configuration options
23
24
**Options:**
25
- `base` (string): Base IRI to use (default: input URL if string, empty string otherwise)
26
- `expandContext` (any): Context to expand with
27
- `issuer` (IdentifierIssuer): Custom identifier issuer for blank nodes
28
- `documentLoader` (function): Custom document loader
29
30
**Usage Examples:**
31
32
```javascript
33
const jsonld = require('jsonld');
34
35
// Basic node map creation
36
const doc = {
37
"@context": {"name": "http://schema.org/name"},
38
"@id": "http://example.org/people/jane",
39
"name": "Jane Doe",
40
"knows": {
41
"@id": "http://example.org/people/john",
42
"name": "John Doe"
43
}
44
};
45
46
const nodeMap = await jsonld.createNodeMap(doc);
47
// Result: {
48
// "http://example.org/people/jane": { "@id": "http://example.org/people/jane", ... },
49
// "http://example.org/people/john": { "@id": "http://example.org/people/john", ... }
50
// }
51
52
// Create node map with custom identifier issuer
53
const IdentifierIssuer = jsonld.util.IdentifierIssuer;
54
const issuer = new IdentifierIssuer('_:custom');
55
56
const nodeMap2 = await jsonld.createNodeMap(doc, {
57
issuer: issuer
58
});
59
```
60
61
### Merge Documents
62
63
Merges multiple JSON-LD documents into a single flattened document, optionally compacted according to a context.
64
65
```javascript { .api }
66
/**
67
* Merges multiple JSON-LD documents
68
* @param docs - Array of JSON-LD documents to merge
69
* @param ctx - Context for compaction (or null)
70
* @param options - Optional configuration object
71
* @returns Promise resolving to merged output
72
*/
73
function merge(docs, ctx, options);
74
```
75
76
**Parameters:**
77
- `docs` (any[]): Array of JSON-LD documents to merge
78
- `ctx` (any): Context for compaction (or null for no compaction)
79
- `options` (MergeOptions, optional): Configuration options
80
81
**Options:**
82
- `base` (string): Base IRI to use
83
- `expandContext` (any): Context to expand with
84
- `issuer` (IdentifierIssuer): Custom identifier issuer for blank nodes
85
- `mergeNodes` (boolean): Merge properties for nodes with same ID (default: true)
86
- `documentLoader` (function): Custom document loader
87
- `safe` (boolean): Use safe mode
88
89
**Usage Examples:**
90
91
```javascript
92
// Basic document merging
93
const doc1 = {
94
"@context": {"name": "http://schema.org/name"},
95
"@id": "http://example.org/people/jane",
96
"name": "Jane Doe"
97
};
98
99
const doc2 = {
100
"@context": {"email": "http://schema.org/email"},
101
"@id": "http://example.org/people/jane",
102
"email": "jane@example.org"
103
};
104
105
const merged = await jsonld.merge([doc1, doc2]);
106
// Result: Merged document with both name and email
107
108
// Merge with compaction
109
const context = {
110
"name": "http://schema.org/name",
111
"email": "http://schema.org/email"
112
};
113
114
const mergedCompacted = await jsonld.merge([doc1, doc2], context);
115
116
// Merge without node merging (preserve separate nodes)
117
const mergedSeparate = await jsonld.merge([doc1, doc2], null, {
118
mergeNodes: false
119
});
120
```
121
122
### Link Documents
123
124
Experimental feature that links JSON-LD document nodes in memory by creating references between related nodes.
125
126
```javascript { .api }
127
/**
128
* Links JSON-LD document nodes in memory
129
* @param input - The JSON-LD document to link
130
* @param ctx - Optional JSON-LD context
131
* @param options - Optional configuration object
132
* @returns Promise resolving to linked output
133
*/
134
function link(input, ctx, options);
135
```
136
137
**Parameters:**
138
- `input` (any): JSON-LD document to link
139
- `ctx` (any, optional): JSON-LD context to apply
140
- `options` (LinkOptions, optional): Configuration options
141
142
**Note:** This is an experimental API that may change. It's implemented as a specialized framing operation with `@embed: '@link'`.
143
144
**Usage Examples:**
145
146
```javascript
147
// Basic linking
148
const doc = {
149
"@context": {"knows": "http://schema.org/knows"},
150
"@graph": [
151
{"@id": "http://example.org/people/jane", "knows": {"@id": "http://example.org/people/john"}},
152
{"@id": "http://example.org/people/john", "name": "John Doe"}
153
]
154
};
155
156
const linked = await jsonld.link(doc);
157
// Result: Document with nodes linked by references
158
159
// Link with context
160
const context = {"name": "http://schema.org/name", "knows": "http://schema.org/knows"};
161
const linkedWithContext = await jsonld.link(doc, context);
162
```
163
164
## Utility Functions
165
166
The `jsonld.util` object provides comprehensive utility functions for JSON-LD data manipulation.
167
168
### Identifier Issuer
169
170
```javascript { .api }
171
/**
172
* Class for issuing unique identifiers for blank nodes
173
*/
174
class IdentifierIssuer {
175
constructor(prefix);
176
getId(existing);
177
hasId(existing);
178
getOldIds();
179
}
180
```
181
182
**Usage Examples:**
183
184
```javascript
185
const IdentifierIssuer = jsonld.util.IdentifierIssuer;
186
187
// Create identifier issuer
188
const issuer = new IdentifierIssuer('_:b');
189
190
// Get identifier for blank node
191
const id1 = issuer.getId('_:temp1'); // Returns '_:b0'
192
const id2 = issuer.getId('_:temp2'); // Returns '_:b1'
193
const id1again = issuer.getId('_:temp1'); // Returns '_:b0' (same as before)
194
195
// Check if identifier exists
196
const hasId = issuer.hasId('_:temp1'); // true
197
198
// Get mapping of old to new IDs
199
const oldIds = issuer.getOldIds(); // ['_:temp1', '_:temp2']
200
```
201
202
### Data Cloning
203
204
```javascript { .api }
205
/**
206
* Deep clones a value, handling objects, arrays, Maps, Sets
207
* @param value - The value to clone
208
* @returns Cloned value
209
*/
210
function clone(value);
211
```
212
213
**Usage Examples:**
214
215
```javascript
216
// Clone JSON-LD document
217
const doc = {
218
"@context": {"name": "http://schema.org/name"},
219
"name": "Jane Doe",
220
"friends": ["Alice", "Bob"]
221
};
222
223
const cloned = jsonld.util.clone(doc);
224
// cloned is a deep copy, modifications won't affect original
225
226
// Clone arrays
227
const arr = [1, 2, {a: 3}];
228
const clonedArr = jsonld.util.clone(arr);
229
230
// Clone Maps and Sets
231
const map = new Map([['key', 'value']]);
232
const clonedMap = jsonld.util.clone(map);
233
```
234
235
### Array Utilities
236
237
```javascript { .api }
238
/**
239
* Ensures a value is an array
240
* @param value - The value to convert
241
* @returns Array containing the value or the value itself if already array
242
*/
243
function asArray(value);
244
```
245
246
**Usage Examples:**
247
248
```javascript
249
// Convert single value to array
250
const single = "value";
251
const arr1 = jsonld.util.asArray(single); // ["value"]
252
253
// Array remains array
254
const multiple = ["a", "b", "c"];
255
const arr2 = jsonld.util.asArray(multiple); // ["a", "b", "c"]
256
```
257
258
### Value Manipulation
259
260
```javascript { .api }
261
/**
262
* Adds a value to a subject property
263
*/
264
function addValue(subject, property, value, options);
265
266
/**
267
* Gets all values for a subject's property as an array
268
*/
269
function getValues(subject, property);
270
271
/**
272
* Removes a property from a subject
273
*/
274
function removeProperty(subject, property);
275
276
/**
277
* Removes a specific value from a subject property
278
*/
279
function removeValue(subject, property, value, options);
280
281
/**
282
* Checks if subject has a property with values
283
*/
284
function hasProperty(subject, property);
285
286
/**
287
* Checks if subject has a specific value for a property
288
*/
289
function hasValue(subject, property, value);
290
```
291
292
**Usage Examples:**
293
294
```javascript
295
const util = jsonld.util;
296
297
// Working with JSON-LD subjects
298
const subject = {"@id": "http://example.org/person"};
299
300
// Add values
301
util.addValue(subject, "name", "Jane Doe");
302
util.addValue(subject, "email", "jane@example.org");
303
util.addValue(subject, "email", "jane.doe@example.org"); // Multiple values
304
305
// Get values
306
const names = util.getValues(subject, "name"); // ["Jane Doe"]
307
const emails = util.getValues(subject, "email"); // ["jane@example.org", "jane.doe@example.org"]
308
309
// Check for properties and values
310
const hasName = util.hasProperty(subject, "name"); // true
311
const hasSpecificEmail = util.hasValue(subject, "email", "jane@example.org"); // true
312
313
// Remove values
314
util.removeValue(subject, "email", "jane@example.org");
315
util.removeProperty(subject, "name");
316
```
317
318
### Blank Node Utilities
319
320
```javascript { .api }
321
/**
322
* Relabels all blank nodes in JSON-LD input
323
* @param input - JSON-LD input
324
* @param options - Optional configuration with issuer
325
* @returns Input with relabeled blank nodes
326
*/
327
function relabelBlankNodes(input, options);
328
329
/**
330
* Regular expression for validating BCP47 language tags
331
*/
332
const REGEX_BCP47;
333
334
/**
335
* Regular expression for validating JSON-LD keywords
336
*/
337
const REGEX_KEYWORD;
338
```
339
340
**Usage Examples:**
341
342
```javascript
343
// Relabel blank nodes with default issuer
344
const doc = {
345
"@id": "_:temp1",
346
"knows": {"@id": "_:temp2"}
347
};
348
349
const relabeled = jsonld.util.relabelBlankNodes(doc);
350
// Result: {"@id": "_:b0", "knows": {"@id": "_:b1"}}
351
352
// Relabel with custom issuer
353
const customIssuer = new jsonld.util.IdentifierIssuer('_:custom');
354
const relabeled2 = jsonld.util.relabelBlankNodes(doc, {issuer: customIssuer});
355
// Result: {"@id": "_:custom0", "knows": {"@id": "_:custom1"}}
356
357
// Use regular expressions for validation
358
const isValidLanguage = jsonld.util.REGEX_BCP47.test('en-US'); // true
359
const isKeyword = jsonld.util.REGEX_KEYWORD.test('@context'); // true
360
```
361
362
### Comparison Utilities
363
364
```javascript { .api }
365
/**
366
* Compares two JSON-LD values for equality
367
* @param v1 - First value
368
* @param v2 - Second value
369
* @returns true if values are equal
370
*/
371
function compareValues(v1, v2);
372
373
/**
374
* Compares strings by length first, then lexicographically
375
* @param a - First string
376
* @param b - Second string
377
* @returns -1, 0, or 1
378
*/
379
function compareShortestLeast(a, b);
380
381
/**
382
* Validates @type value format and throws on invalid values
383
* @param v - Value to validate
384
* @param isFrame - Whether validation is for framing context
385
*/
386
function validateTypeValue(v, isFrame);
387
388
/**
389
* Builds HTTP headers object for JSON-LD requests
390
* @param headers - Custom headers object
391
* @returns Headers object with valid Accept header
392
*/
393
function buildHeaders(headers);
394
395
/**
396
* Parses Link headers and returns structured results
397
* @param header - Link header string to parse
398
* @returns Object keyed by rel values
399
*/
400
function parseLinkHeader(header);
401
```
402
403
**Usage Examples:**
404
405
```javascript
406
const util = jsonld.util;
407
408
// Compare JSON-LD values
409
const val1 = {"@value": "test", "@type": "http://www.w3.org/2001/XMLSchema#string"};
410
const val2 = {"@value": "test", "@type": "http://www.w3.org/2001/XMLSchema#string"};
411
const equal = util.compareValues(val1, val2); // true
412
413
// Compare strings
414
const result1 = util.compareShortestLeast("a", "aa"); // -1 (shorter first)
415
const result2 = util.compareShortestLeast("aa", "ab"); // -1 (lexicographic)
416
const result3 = util.compareShortestLeast("test", "test"); // 0 (equal)
417
418
// Validate @type values
419
try {
420
jsonld.util.validateTypeValue({"@value": "invalid"}, false);
421
} catch (error) {
422
console.log('Invalid @type value');
423
}
424
425
// Build headers for JSON-LD requests
426
const headers = jsonld.util.buildHeaders({
427
'User-Agent': 'MyApp/1.0'
428
});
429
// Result: { Accept: 'application/ld+json, application/json', 'User-Agent': 'MyApp/1.0' }
430
431
// Parse Link headers
432
const linkHeader = '<http://example.org/context>; rel="http://www.w3.org/ns/json-ld#context"';
433
const parsed = jsonld.util.parseLinkHeader(linkHeader);
434
// Result: { 'http://www.w3.org/ns/json-ld#context': { target: 'http://example.org/context', rel: '...' } }
435
436
// Access legacy RequestQueue (for backward compatibility)
437
const RequestQueue = jsonld.RequestQueue;
438
const queue = new RequestQueue();
439
// Note: RequestQueue is a legacy component maintained for backward compatibility
440
```
441
442
## Types
443
444
```javascript { .api }
445
/**
446
* Options for createNodeMap operations
447
*/
448
interface NodeMapOptions extends JsonLdOptions {
449
issuer?: IdentifierIssuer;
450
}
451
452
/**
453
* Options for merge operations
454
*/
455
interface MergeOptions extends JsonLdOptions {
456
issuer?: IdentifierIssuer;
457
mergeNodes?: boolean;
458
}
459
460
/**
461
* Options for link operations
462
*/
463
interface LinkOptions extends JsonLdOptions {
464
// Inherits all JsonLdOptions
465
}
466
467
/**
468
* Options for addValue operations
469
*/
470
interface AddValueOptions {
471
propertyIsArray?: boolean;
472
valueIsArray?: boolean;
473
allowDuplicate?: boolean;
474
prependValue?: boolean;
475
}
476
477
/**
478
* Options for removeValue operations
479
*/
480
interface RemoveValueOptions {
481
propertyIsArray?: boolean;
482
}
483
484
/**
485
* Options for relabelBlankNodes operations
486
*/
487
interface RelabelOptions {
488
issuer?: IdentifierIssuer;
489
}
490
491
/**
492
* Node map structure (maps node IDs to node objects)
493
*/
494
type NodeMap = Record<string, JsonLdNode>;
495
496
/**
497
* JSON-LD node structure
498
*/
499
interface JsonLdNode {
500
'@id': string;
501
[property: string]: any;
502
}
503
```