A comprehensive JSON-LD Processor and API implementation in JavaScript for processing Linked Data in JSON format
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
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.
Creates a merged node map from JSON-LD input, flattening all nodes into a single map indexed by node ID.
/**
* Creates a merged node map from JSON-LD input
* @param input - The JSON-LD input
* @param options - Optional configuration object
* @returns Promise resolving to merged node map
*/
function createNodeMap(input, options);Parameters:
input (any): JSON-LD input to processoptions (NodeMapOptions, optional): Configuration optionsOptions:
base (string): Base IRI to use (default: input URL if string, empty string otherwise)expandContext (any): Context to expand withissuer (IdentifierIssuer): Custom identifier issuer for blank nodesdocumentLoader (function): Custom document loaderUsage Examples:
const jsonld = require('jsonld');
// Basic node map creation
const doc = {
"@context": {"name": "http://schema.org/name"},
"@id": "http://example.org/people/jane",
"name": "Jane Doe",
"knows": {
"@id": "http://example.org/people/john",
"name": "John Doe"
}
};
const nodeMap = await jsonld.createNodeMap(doc);
// Result: {
// "http://example.org/people/jane": { "@id": "http://example.org/people/jane", ... },
// "http://example.org/people/john": { "@id": "http://example.org/people/john", ... }
// }
// Create node map with custom identifier issuer
const IdentifierIssuer = jsonld.util.IdentifierIssuer;
const issuer = new IdentifierIssuer('_:custom');
const nodeMap2 = await jsonld.createNodeMap(doc, {
issuer: issuer
});Merges multiple JSON-LD documents into a single flattened document, optionally compacted according to a context.
/**
* Merges multiple JSON-LD documents
* @param docs - Array of JSON-LD documents to merge
* @param ctx - Context for compaction (or null)
* @param options - Optional configuration object
* @returns Promise resolving to merged output
*/
function merge(docs, ctx, options);Parameters:
docs (any[]): Array of JSON-LD documents to mergectx (any): Context for compaction (or null for no compaction)options (MergeOptions, optional): Configuration optionsOptions:
base (string): Base IRI to useexpandContext (any): Context to expand withissuer (IdentifierIssuer): Custom identifier issuer for blank nodesmergeNodes (boolean): Merge properties for nodes with same ID (default: true)documentLoader (function): Custom document loadersafe (boolean): Use safe modeUsage Examples:
// Basic document merging
const doc1 = {
"@context": {"name": "http://schema.org/name"},
"@id": "http://example.org/people/jane",
"name": "Jane Doe"
};
const doc2 = {
"@context": {"email": "http://schema.org/email"},
"@id": "http://example.org/people/jane",
"email": "jane@example.org"
};
const merged = await jsonld.merge([doc1, doc2]);
// Result: Merged document with both name and email
// Merge with compaction
const context = {
"name": "http://schema.org/name",
"email": "http://schema.org/email"
};
const mergedCompacted = await jsonld.merge([doc1, doc2], context);
// Merge without node merging (preserve separate nodes)
const mergedSeparate = await jsonld.merge([doc1, doc2], null, {
mergeNodes: false
});Experimental feature that links JSON-LD document nodes in memory by creating references between related nodes.
/**
* Links JSON-LD document nodes in memory
* @param input - The JSON-LD document to link
* @param ctx - Optional JSON-LD context
* @param options - Optional configuration object
* @returns Promise resolving to linked output
*/
function link(input, ctx, options);Parameters:
input (any): JSON-LD document to linkctx (any, optional): JSON-LD context to applyoptions (LinkOptions, optional): Configuration optionsNote: This is an experimental API that may change. It's implemented as a specialized framing operation with @embed: '@link'.
Usage Examples:
// Basic linking
const doc = {
"@context": {"knows": "http://schema.org/knows"},
"@graph": [
{"@id": "http://example.org/people/jane", "knows": {"@id": "http://example.org/people/john"}},
{"@id": "http://example.org/people/john", "name": "John Doe"}
]
};
const linked = await jsonld.link(doc);
// Result: Document with nodes linked by references
// Link with context
const context = {"name": "http://schema.org/name", "knows": "http://schema.org/knows"};
const linkedWithContext = await jsonld.link(doc, context);The jsonld.util object provides comprehensive utility functions for JSON-LD data manipulation.
/**
* Class for issuing unique identifiers for blank nodes
*/
class IdentifierIssuer {
constructor(prefix);
getId(existing);
hasId(existing);
getOldIds();
}Usage Examples:
const IdentifierIssuer = jsonld.util.IdentifierIssuer;
// Create identifier issuer
const issuer = new IdentifierIssuer('_:b');
// Get identifier for blank node
const id1 = issuer.getId('_:temp1'); // Returns '_:b0'
const id2 = issuer.getId('_:temp2'); // Returns '_:b1'
const id1again = issuer.getId('_:temp1'); // Returns '_:b0' (same as before)
// Check if identifier exists
const hasId = issuer.hasId('_:temp1'); // true
// Get mapping of old to new IDs
const oldIds = issuer.getOldIds(); // ['_:temp1', '_:temp2']/**
* Deep clones a value, handling objects, arrays, Maps, Sets
* @param value - The value to clone
* @returns Cloned value
*/
function clone(value);Usage Examples:
// Clone JSON-LD document
const doc = {
"@context": {"name": "http://schema.org/name"},
"name": "Jane Doe",
"friends": ["Alice", "Bob"]
};
const cloned = jsonld.util.clone(doc);
// cloned is a deep copy, modifications won't affect original
// Clone arrays
const arr = [1, 2, {a: 3}];
const clonedArr = jsonld.util.clone(arr);
// Clone Maps and Sets
const map = new Map([['key', 'value']]);
const clonedMap = jsonld.util.clone(map);/**
* Ensures a value is an array
* @param value - The value to convert
* @returns Array containing the value or the value itself if already array
*/
function asArray(value);Usage Examples:
// Convert single value to array
const single = "value";
const arr1 = jsonld.util.asArray(single); // ["value"]
// Array remains array
const multiple = ["a", "b", "c"];
const arr2 = jsonld.util.asArray(multiple); // ["a", "b", "c"]/**
* Adds a value to a subject property
*/
function addValue(subject, property, value, options);
/**
* Gets all values for a subject's property as an array
*/
function getValues(subject, property);
/**
* Removes a property from a subject
*/
function removeProperty(subject, property);
/**
* Removes a specific value from a subject property
*/
function removeValue(subject, property, value, options);
/**
* Checks if subject has a property with values
*/
function hasProperty(subject, property);
/**
* Checks if subject has a specific value for a property
*/
function hasValue(subject, property, value);Usage Examples:
const util = jsonld.util;
// Working with JSON-LD subjects
const subject = {"@id": "http://example.org/person"};
// Add values
util.addValue(subject, "name", "Jane Doe");
util.addValue(subject, "email", "jane@example.org");
util.addValue(subject, "email", "jane.doe@example.org"); // Multiple values
// Get values
const names = util.getValues(subject, "name"); // ["Jane Doe"]
const emails = util.getValues(subject, "email"); // ["jane@example.org", "jane.doe@example.org"]
// Check for properties and values
const hasName = util.hasProperty(subject, "name"); // true
const hasSpecificEmail = util.hasValue(subject, "email", "jane@example.org"); // true
// Remove values
util.removeValue(subject, "email", "jane@example.org");
util.removeProperty(subject, "name");/**
* Relabels all blank nodes in JSON-LD input
* @param input - JSON-LD input
* @param options - Optional configuration with issuer
* @returns Input with relabeled blank nodes
*/
function relabelBlankNodes(input, options);
/**
* Regular expression for validating BCP47 language tags
*/
const REGEX_BCP47;
/**
* Regular expression for validating JSON-LD keywords
*/
const REGEX_KEYWORD;Usage Examples:
// Relabel blank nodes with default issuer
const doc = {
"@id": "_:temp1",
"knows": {"@id": "_:temp2"}
};
const relabeled = jsonld.util.relabelBlankNodes(doc);
// Result: {"@id": "_:b0", "knows": {"@id": "_:b1"}}
// Relabel with custom issuer
const customIssuer = new jsonld.util.IdentifierIssuer('_:custom');
const relabeled2 = jsonld.util.relabelBlankNodes(doc, {issuer: customIssuer});
// Result: {"@id": "_:custom0", "knows": {"@id": "_:custom1"}}
// Use regular expressions for validation
const isValidLanguage = jsonld.util.REGEX_BCP47.test('en-US'); // true
const isKeyword = jsonld.util.REGEX_KEYWORD.test('@context'); // true/**
* Compares two JSON-LD values for equality
* @param v1 - First value
* @param v2 - Second value
* @returns true if values are equal
*/
function compareValues(v1, v2);
/**
* Compares strings by length first, then lexicographically
* @param a - First string
* @param b - Second string
* @returns -1, 0, or 1
*/
function compareShortestLeast(a, b);
/**
* Validates @type value format and throws on invalid values
* @param v - Value to validate
* @param isFrame - Whether validation is for framing context
*/
function validateTypeValue(v, isFrame);
/**
* Builds HTTP headers object for JSON-LD requests
* @param headers - Custom headers object
* @returns Headers object with valid Accept header
*/
function buildHeaders(headers);
/**
* Parses Link headers and returns structured results
* @param header - Link header string to parse
* @returns Object keyed by rel values
*/
function parseLinkHeader(header);Usage Examples:
const util = jsonld.util;
// Compare JSON-LD values
const val1 = {"@value": "test", "@type": "http://www.w3.org/2001/XMLSchema#string"};
const val2 = {"@value": "test", "@type": "http://www.w3.org/2001/XMLSchema#string"};
const equal = util.compareValues(val1, val2); // true
// Compare strings
const result1 = util.compareShortestLeast("a", "aa"); // -1 (shorter first)
const result2 = util.compareShortestLeast("aa", "ab"); // -1 (lexicographic)
const result3 = util.compareShortestLeast("test", "test"); // 0 (equal)
// Validate @type values
try {
jsonld.util.validateTypeValue({"@value": "invalid"}, false);
} catch (error) {
console.log('Invalid @type value');
}
// Build headers for JSON-LD requests
const headers = jsonld.util.buildHeaders({
'User-Agent': 'MyApp/1.0'
});
// Result: { Accept: 'application/ld+json, application/json', 'User-Agent': 'MyApp/1.0' }
// Parse Link headers
const linkHeader = '<http://example.org/context>; rel="http://www.w3.org/ns/json-ld#context"';
const parsed = jsonld.util.parseLinkHeader(linkHeader);
// Result: { 'http://www.w3.org/ns/json-ld#context': { target: 'http://example.org/context', rel: '...' } }
// Access legacy RequestQueue (for backward compatibility)
const RequestQueue = jsonld.RequestQueue;
const queue = new RequestQueue();
// Note: RequestQueue is a legacy component maintained for backward compatibility/**
* Options for createNodeMap operations
*/
interface NodeMapOptions extends JsonLdOptions {
issuer?: IdentifierIssuer;
}
/**
* Options for merge operations
*/
interface MergeOptions extends JsonLdOptions {
issuer?: IdentifierIssuer;
mergeNodes?: boolean;
}
/**
* Options for link operations
*/
interface LinkOptions extends JsonLdOptions {
// Inherits all JsonLdOptions
}
/**
* Options for addValue operations
*/
interface AddValueOptions {
propertyIsArray?: boolean;
valueIsArray?: boolean;
allowDuplicate?: boolean;
prependValue?: boolean;
}
/**
* Options for removeValue operations
*/
interface RemoveValueOptions {
propertyIsArray?: boolean;
}
/**
* Options for relabelBlankNodes operations
*/
interface RelabelOptions {
issuer?: IdentifierIssuer;
}
/**
* Node map structure (maps node IDs to node objects)
*/
type NodeMap = Record<string, JsonLdNode>;
/**
* JSON-LD node structure
*/
interface JsonLdNode {
'@id': string;
[property: string]: any;
}