### Install jsonld.js using JSPM Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This code snippet shows the command to install the jsonld.js library using the JSPM package manager. It also provides examples of how to import the library using different module import syntaxes. ```bash jspm install npm:jsonld ``` ```javascript import * as jsonld from 'jsonld'; // or import {promises} from 'jsonld'; // or import {JsonLdProcessor} from 'jsonld'; ``` -------------------------------- ### Install jsonld.js for Node.js using npm Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md Installs the jsonld.js library for use in Node.js environments via the npm package manager. This is the primary method for integrating the library into server-side JavaScript projects. ```bash npm install jsonld ``` -------------------------------- ### JSON-LD Example Data and Context Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code defines example data ('doc') and a context ('context') that are used throughout the subsequent JSON-LD processing examples. The 'doc' represents a simple JSON object, and 'context' maps short keys to full IRIs, including type information. ```javascript const doc = { "http://schema.org/name": "Manu Sporny", "http://schema.org/url": {"@id": "http://manu.sporny.org/"}, "http://schema.org/image": {"@id": "http://manu.sporny.org/images/manu.png"} }; const context = { "name": "http://schema.org/name", "homepage": {"@id": "http://schema.org/url", "@type": "@id"}, "image": {"@id": "http://schema.org/image", "@type": "@id"} }; ``` -------------------------------- ### React Native Setup for jsonld.js Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md To use jsonld.js with React Native, a polyfill like data-integrity-rn must be imported first. This polyfill provides necessary globals such as crypto.subtle and TextEncoder, which are required by the jsonld.js library for its operations. ```javascript import '@digitalcredentials/data-integrity-rn' import * as jsonld from 'jsonld' ``` -------------------------------- ### Custom Document Loader Configuration Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Custom document loaders fetch remote JSON-LD contexts and documents, enabling caching, authentication, and offline operation. This example shows how to create and set a custom loader. Dependencies: jsonld. ```javascript const jsonld = require('jsonld'); // Define pre-loaded contexts const CONTEXTS = { 'https://schema.org': { '@context': { '@vocab': 'https://schema.org/', 'name': 'https://schema.org/name', 'description': 'https://schema.org/description' } }, 'https://example.com/context': { '@context': { 'ex': 'https://example.com/', 'title': 'ex:title', 'author': 'ex:author' } } }; // Create custom document loader with caching const customLoader = async (url, options) => { // Check cache first if (url in CONTEXTS) { return { contextUrl: null, document: CONTEXTS[url], documentUrl: url }; } // Fall back to default loader for other URLs return jsonld.documentLoaders.node()(url, options); }; // Set as default document loader jsonld.documentLoader = customLoader; // Or use per-call const doc = { '@context': 'https://example.com/context', 'title': 'My Document' }; const expanded = await jsonld.expand(doc, {documentLoader: customLoader}); console.log(JSON.stringify(expanded, null, 2)); ``` -------------------------------- ### Flatten JSON-LD Document Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code provides an example of flattening a JSON-LD document. Flattening merges all nested JSON-LD trees into a single top-level structure, simplifying the document's representation. ```javascript // flatten a document const flattened = await jsonld.flatten(doc); // output has all deep-level trees flattened to the top-level ``` -------------------------------- ### Compact JSON-LD Document Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code demonstrates how to compact a JSON-LD document using a provided context. It shows both compacting a local document object and suggests compacting using URLs. The output is a more concise JSON representation. ```javascript // compact a document according to a particular context const compacted = await jsonld.compact(doc, context); console.log(JSON.stringify(compacted, null, 2)); /* Output: { "@context": {...}, "name": "Manu Sporny", "homepage": "http://manu.sporny.org/", "image": "http://manu.sporny.org/images/manu.png" } */ // compact using URLs const compacted = await jsonld.compact( 'http://example.org/doc', 'http://example.org/context', ...); ``` -------------------------------- ### Include jsonld.js via unpkg CDN Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This snippet illustrates how to include the jsonld.js library using a script tag from the unpkg CDN. It specifies version 1.0.0 and directs users to the unpkg package page for the most recent version information. ```html ``` -------------------------------- ### Include jsonld.js via jsDeliver CDN Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This snippet demonstrates how to include the jsonld.js library using a script tag from the jsDeliver CDN. It references version 1.0.0 and provides a link to the jsDeliver package page for checking the latest version. ```html ``` -------------------------------- ### Custom Document Loader in jsonld.js Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md Demonstrates how to override the default document loader in jsonld.js with a custom one, allowing for pre-loaded contexts or custom loading logic. It shows how to define a mapping of context URLs to context documents and create a custom loader function that checks the mapping before falling back to the default loader. This is useful for controlling how external JSON-LD contexts are fetched. ```javascript // how to override the default document loader with a custom one -- for // example, one that uses pre-loaded contexts: // define a mapping of context URL => context doc const CONTEXTS = { "http://example.com": { "@context": ... }, ... }; // grab the built-in Node.js doc loader const nodeDocumentLoader = jsonld.documentLoaders.node(); // or grab the XHR one: jsonld.documentLoaders.xhr() // change the default document loader const customLoader = async (url, options) => { if(url in CONTEXTS) { return { contextUrl: null, // this is for a context via a link header document: CONTEXTS[url], // this is the actual document that was loaded documentUrl: url // this is the actual context URL after redirects }; } // call the default documentLoader return nodeDocumentLoader(url); }; jsonld.documentLoader = customLoader; // alternatively, pass the custom loader for just a specific call: const compacted = await jsonld.compact( doc, context, {documentLoader: customLoader}); ``` -------------------------------- ### Use jsonld.js browser bundle (AMD) Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md Loads the jsonld.js library in a browser environment using an AMD (Asynchronous Module Definition) loader. This typically involves specifying the path to the bundled JavaScript file. ```bash Use your favorite technology to load node_modules/dist/jsonld.min.js. ``` -------------------------------- ### Expand JSON-LD Document Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code illustrates how to expand a JSON-LD document, effectively removing its context and returning it to its fully expanded form with IRIs. It shows expanding a compacted document and suggests expanding using URLs. ```javascript // expand a document, removing its context const expanded = await jsonld.expand(compacted); /* Output: { "http://schema.org/name": [{"@value": "Manu Sporny"}], "http://schema.org/url": [{"@id": "http://manu.sporny.org/"}], "http://schema.org/image": [{"@id": "http://manu.sporny.org/images/manu.png"}] } */ // expand using URLs const expanded = await jsonld.expand('http://example.org/doc', ...); ``` -------------------------------- ### Include jsonld.js via CDNJS Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This snippet shows how to include the jsonld.js library in your HTML using a script tag from the CDNJS CDN. It points to a specific version (1.0.0) and suggests checking the CDNJS library page for the latest available version. ```html ``` -------------------------------- ### Import jsonld.js in JavaScript (CommonJS and ES Modules) Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Demonstrates how to import the jsonld.js library in JavaScript projects. It covers both CommonJS (`require`) for Node.js environments and ES Modules (`import`) for modern JavaScript development. ```javascript // CommonJS const jsonld = require('jsonld'); ``` ```javascript // ES Modules import jsonld from 'jsonld'; ``` -------------------------------- ### Compact JSON-LD Data - Apply Context to Expanded Data Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt The `compact` method applies a JSON-LD context to data, shortening IRIs to human-readable terms and creating a more concise document. This is the inverse operation of expansion and is useful for generating user-friendly JSON-LD. Options can be provided to customize the compaction behavior. ```javascript const jsonld = require('jsonld'); const doc = { "http://schema.org/name": "Manu Sporny", "http://schema.org/url": {"@id": "http://manu.sporny.org/"}, "http://schema.org/image": {"@id": "http://manu.sporny.org/images/manu.png"} }; const context = { "name": "http://schema.org/name", "homepage": {"@id": "http://schema.org/url", "@type": "@id"}, "image": {"@id": "http://schema.org/image", "@type": "@id"} }; const compacted = await jsonld.compact(doc, context); console.log(JSON.stringify(compacted, null, 2)); /* Output: { "@context": { "name": "http://schema.org/name", "homepage": {"@id": "http://schema.org/url", "@type": "@id"}, "image": {"@id": "http://schema.org/image", "@type": "@id"} }, "name": "Manu Sporny", "homepage": "http://manu.sporny.org/", "image": "http://manu.sporny.org/images/manu.png" } */ // Compact with options const compactedWithOptions = await jsonld.compact(doc, context, { compactArrays: true, // Compact arrays with single values compactToRelative: true, // Compact IRIs relative to document base graph: false, // Don't force top-level @graph safe: true // Enable safe mode }); ``` -------------------------------- ### Register Custom Synchronous RDF Parser Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code demonstrates how to register a custom synchronous RDF parser with jsonld.js. The provided function takes a content type and an input string, parses it into a jsonld.js RDF dataset object, and returns the dataset. ```javascript // register a custom synchronous RDF parser jsonld.registerRDFParser(contentType, input => { // parse input to a jsonld.js RDF dataset object... and return it return dataset; }); ``` -------------------------------- ### Node.js Document Loader Configuration Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Configure the built-in Node.js document loader with custom headers, agents, and security settings for fetching remote documents. Dependencies: jsonld, https. ```javascript const jsonld = require('jsonld'); const https = require('https'); // Configure Node.js document loader const nodeLoader = jsonld.documentLoaders.node({ secure: true, // Require HTTPS strictSSL: true, // Validate SSL certificates maxRedirects: 5, // Maximum redirect hops headers: { 'User-Agent': 'MyApp/1.0', 'Authorization': 'Bearer token123' }, httpsAgent: new https.Agent({ rejectUnauthorized: true, keepAlive: true }) }); jsonld.documentLoader = nodeLoader; // Use the configured loader const doc = await jsonld.expand('https://example.com/document.jsonld'); ``` -------------------------------- ### Register Custom Promise-based RDF Parser Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code illustrates how to register a custom asynchronous (Promise-based) RDF parser with jsonld.js. The function accepts a content type and input, parses it asynchronously into a jsonld.js RDF dataset object, and returns a Promise that resolves with the dataset. ```javascript // register a custom promise-based RDF parser jsonld.registerRDFParser(contentType, async input => { // parse input into a jsonld.js RDF dataset object... return new Promise(...); }); ``` -------------------------------- ### Import jsonld.js in Node.js using CommonJS Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md Imports the jsonld.js library into a Node.js module using the CommonJS module system. This allows you to access the library's functionalities within your JavaScript code. ```javascript const jsonld = require('jsonld'); ``` -------------------------------- ### Import jsonld.js in Node.js using ES Modules Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md Imports the jsonld.js library into a Node.js module using the ES Modules system. This is an alternative to CommonJS for importing modules in modern JavaScript environments. ```javascript import jsonld from 'jsonld'; ``` -------------------------------- ### Serialize JSON-LD to N-Quads (RDF) Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code demonstrates how to serialize a JSON-LD document into the N-Quads RDF format. The resulting 'nquads' variable will contain a string representation of the RDF data. ```javascript // serialize a document to N-Quads (RDF) const nquads = await jsonld.toRDF(doc, {format: 'application/n-quads'}); // nquads is a string of N-Quads ``` -------------------------------- ### JsonLdProcessor WebIDL API in JavaScript Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Implements a WebIDL-compliant interface for JSON-LD processing, matching the W3C JSON-LD API specification. It provides static methods for common operations like compact, expand, and flatten, returning Promises. ```javascript const jsonld = require('jsonld'); const JsonLdProcessor = jsonld.JsonLdProcessor; // Static methods matching W3C spec const compacted = await JsonLdProcessor.compact(doc, context); const expanded = await JsonLdProcessor.expand(doc); const flattened = await JsonLdProcessor.flatten(doc); // These return Promises and have the same behavior as jsonld.* methods ``` -------------------------------- ### URL Utilities for IRIs in JavaScript Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Provides functions for checking absolute IRIs, parsing URL components, resolving relative URLs against a base, and prepending a base to a relative IRI. These utilities are essential for handling Linked Data URIs. ```javascript const jsonld = require('jsonld'); // Check if a string is an absolute IRI console.log(jsonld.url.isAbsolute('http://example.org/')); // true console.log(jsonld.url.isAbsolute('urn:isbn:123')); // true console.log(jsonld.url.isAbsolute('_:blank')); // true (blank node) console.log(jsonld.url.isAbsolute('relative/path')); // false // Parse URL components const parsed = jsonld.url.parse('http://example.org:8080/path?query=1#hash'); console.log(parsed); /* Output: {scheme, authority, path, query, fragment} */ // Resolve relative URLs const base = 'http://example.org/base/'; const relative = '../other/path'; const resolved = jsonld.url.resolve(base, relative); console.log(resolved); // 'http://example.org/other/path' // Prepend base to relative IRI const full = jsonld.url.prependBase('http://example.org/', 'resource'); console.log(full); // 'http://example.org/resource' ``` -------------------------------- ### Enable Safe Mode for JSON-LD Expansion in jsonld.js Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md Explains how to use the 'safe mode' in jsonld.js to prevent lossy JSON-LD operations, particularly useful for digital signing. When enabled, this mode will cause processing to fail if it detects situations that would result in data loss according to the JSON-LD specifications. The 'safe' option flag set to `true` activates this behavior. ```javascript // expand a document in safe mode const expanded = await jsonld.expand(data, {safe: true}); ``` -------------------------------- ### Canonize (Normalize) JSON-LD Document Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code shows how to canonize (normalize) a JSON-LD document using the RDF Dataset Canonicalization Algorithm (URDNA2015). The output is a canonical string representation suitable for hashing or comparison. ```javascript // canonize (normalize) a document using the RDF Dataset Canonicalization Algorithm // (URDNA2015): const canonized = await jsonld.canonize(doc, { algorithm: 'URDNA2015', format: 'application/n-quads' }); // canonized is a string that is a canonical representation of the document // that can be used for hashing, comparison, etc. ``` -------------------------------- ### Expand JSON-LD Document - Remove Context and Expand IRIs Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt The `expand` method in jsonld.js processes a JSON-LD document to remove its context and expand all property names to their full IRI forms. This results in a normalized, unambiguous representation of the data. It can also accept options for controlling the expansion process. ```javascript const jsonld = require('jsonld'); const doc = { "@context": { "name": "http://schema.org/name", "homepage": {"@id": "http://schema.org/url", "@type": "@id"} }, "name": "Manu Sporny", "homepage": "http://manu.sporny.org/" }; const expanded = await jsonld.expand(doc); console.log(JSON.stringify(expanded, null, 2)); /* Output: [ { "http://schema.org/name": [{"@value": "Manu Sporny"}], "http://schema.org/url": [{"@id": "http://manu.sporny.org/"}] } ] */ // Expand with options const expandedWithOptions = await jsonld.expand(doc, { base: 'http://example.org/', safe: true, // Enable safe mode to fail on lossy operations keepFreeFloatingNodes: false }); ``` -------------------------------- ### Canonize JSON-LD to Canonical N-Quads with jsonld.js Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt The `canonize` method (or `normalize`) generates a canonical N-Quads representation of JSON-LD data using the RDF Dataset Canonicalization Algorithm (RDFC-1.0). This is crucial for digital signatures and content verification. It supports various algorithms and input formats, including N-Quads. ```javascript const jsonld = require('jsonld'); const doc = { "@context": {"@vocab": "http://example.org/"}, "@id": "http://example.org/test", "name": "Test Document", "value": 42 }; // Canonize with default options (safe mode enabled by default) const canonized = await jsonld.canonize(doc, { algorithm: 'RDFC-1.0', format: 'application/n-quads' }); console.log(canonized); /* Output: "Test Document" . "42"^^ . */ // Canonize with custom options const canonizedCustom = await jsonld.canonize(doc, { safe: true, base: null, canonizeOptions: { algorithm: 'RDFC-1.0', messageDigestAlgorithm: 'sha256', maxWorkFactor: 1 } }); // Canonize from N-Quads input const nquads = ' "value" .'; const canonizedFromNQuads = await jsonld.canonize(nquads, { inputFormat: 'application/n-quads', algorithm: 'RDFC-1.0' }); ``` -------------------------------- ### Frame JSON-LD Document Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code demonstrates framing a JSON-LD document. Framing transforms the document's structure according to a specified frame, allowing for data to be presented in a desired tree format. ```javascript // frame a document const framed = await jsonld.frame(doc, frame); // output transformed into a particular tree structure per the given frame ``` -------------------------------- ### Register Custom RDF Parser Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Allows registration of custom parsers for different RDF serialization formats, such as 'text/turtle'. After registration, `jsonld.fromRDF` can use this parser. Parsers can also be unregistered. ```javascript const jsonld = require('jsonld'); // Register a custom Turtle parser (example) jsonld.registerRDFParser('text/turtle', async (input) => { // Parse Turtle input and return RDF dataset // This is a placeholder - actual implementation would use a Turtle parser const quads = []; // ... parse input into quads ... return quads; }); // Use the custom parser const turtleData = " @prefix schema: . schema:name \"Alice\" . "; const doc = await jsonld.fromRDF(turtleData, {format: 'text/turtle'}); // Unregister parser jsonld.unregisterRDFParser('text/turtle'); ``` -------------------------------- ### Deserialize N-Quads (RDF) to JSON-LD Source: https://github.com/digitalbazaar/jsonld.js/blob/main/README.md This JavaScript code shows how to deserialize a string of N-Quads (RDF) back into a JSON-LD document. The 'doc' variable will then hold the parsed JSON-LD object. ```javascript // deserialize N-Quads (RDF) to JSON-LD const doc = await jsonld.fromRDF(nquads, {format: 'application/n-quads'}); // doc is JSON-LD ``` -------------------------------- ### Create Node Map from Document Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Generates a flattened map of all nodes in a JSON-LD document, keyed by their '@id'. This is useful for efficient lookups and graph traversal. It takes a document as input and returns a Promise that resolves to the node map. ```javascript const jsonld = require('jsonld'); const doc = { "@id": "ex:1", "http://example.org/property": [ {"@id": "ex:2", "http://example.org/name": [{"@value": "Node 2"}]} ] }; const nodeMap = await jsonld.createNodeMap(doc); console.log(JSON.stringify(nodeMap, null, 2)); /* Output: { "ex:1": { "@id": "ex:1", "http://example.org/property": [{"@id": "ex:2"}] }, "ex:2": { "@id": "ex:2", "http://example.org/name": [{"@value": "Node 2"}] } } */ // Access nodes by ID const node2 = nodeMap['ex:2']; console.log(node2['http://example.org/name'][0]['@value']); // "Node 2" ``` -------------------------------- ### Convert RDF to JSON-LD using fromRDF Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt The `fromRDF` method converts RDF data (N-Quads string or dataset) to JSON-LD format. It supports options for native type conversion and RDF direction. Dependencies: jsonld. ```javascript const jsonld = require('jsonld'); const nquads = ` "Alice" . . "Bob" . `; // Convert N-Quads to JSON-LD const doc = await jsonld.fromRDF(nquads, {format: 'application/n-quads'}); console.log(JSON.stringify(doc, null, 2)); // fromRDF with native types conversion const docNative = await jsonld.fromRDF(nquads, { format: 'application/n-quads', useNativeTypes: true, // Convert XSD types to JS native types useRdfType: false, // Use @type instead of rdf:type rdfDirection: 'i18n-datatype' // Support @direction }); ``` -------------------------------- ### Convert JSON-LD to RDF Dataset with jsonld.js Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt The `toRDF` method facilitates the conversion of JSON-LD documents into RDF datasets. The output can be either an internal RDF dataset object representation or a serialized N-Quads string. This method also supports handling of language-tagged strings and directionality for internationalized data. ```javascript const jsonld = require('jsonld'); const doc = { "@context": { "name": "http://schema.org/name", "knows": {"@id": "http://schema.org/knows", "@type": "@id"} }, "@id": "https://example.com/alice", "name": "Alice", "knows": "https://example.com/bob" }; // Convert to N-Quads string const nquads = await jsonld.toRDF(doc, {format: 'application/n-quads'}); console.log(nquads); /* Output: . "Alice" . */ // Convert to RDF dataset object const dataset = await jsonld.toRDF(doc); console.log(dataset); /* Output: Array of quad objects with subject, predicate, object, graph */ // toRDF with direction support const docWithDirection = { "@context": {"@language": "ar", "@direction": "rtl"}, "http://example.org/title": "مثال" }; const nquadsWithDir = await jsonld.toRDF(docWithDirection, { format: 'application/n-quads', rdfDirection: 'i18n-datatype' // Use i18n datatype for @direction }); ``` -------------------------------- ### Implement Event Handlers for JSON-LD Processing Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Event handlers provide fine-grained control over warnings and processing events during JSON-LD operations. They can be defined as a single function or a map of event codes to handler functions. A default event handler can also be set globally. ```javascript const jsonld = require('jsonld'); // Simple event handler function const eventHandler = ({event, next}) => { console.log(`Event [${event.level}]: ${event.code}`); console.log('Details:', JSON.stringify(event.details)); // Call next() to pass to next handler, or return to stop propagation if (event.code === 'invalid property') { console.warn('Undefined property:', event.details.property); return; // Handle this event, don't propagate } next(); // Pass to next handler }; const doc = { "@context": {"name": "http://schema.org/name"}, "name": "Test", "unknownProperty": "will warn" }; const expanded = await jsonld.expand(doc, {eventHandler}); // Event handler as code-to-function map const handlers = { 'invalid property': ({event}) => { console.warn('Dropped property:', event.details.property); }, 'relative @id reference': ({event}) => { console.warn('Relative IRI:', event.details.id); } }; const expanded2 = await jsonld.expand(doc, {eventHandler: handlers}); // Set default event handler for all operations jsonld.setDefaultEventHandler({eventHandler: ({event}) => { if (event.level === 'warning') { console.warn(`Warning: ${event.code}`); } }}); ``` -------------------------------- ### Merge Multiple JSON-LD Documents Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt The `merge` method combines multiple JSON-LD documents into a single flattened document, merging nodes with the same `@id`. It supports an optional compaction context and options to control node merging behavior. Dependencies: jsonld. ```javascript const jsonld = require('jsonld'); const docA = { "@id": "ex:person1", "http://schema.org/name": [{"@value": "Alice"}] }; const docB = { "@id": "ex:person1", "http://schema.org/email": [{"@value": "alice@example.com"}] }; const docC = { "@id": "ex:person2", "http://schema.org/name": [{"@value": "Bob"}] }; // Merge documents const merged = await jsonld.merge([docA, docB, docC]); console.log(JSON.stringify(merged, null, 2)); // Merge with compaction context const context = {'@vocab': 'http://schema.org/'}; const mergedCompacted = await jsonld.merge([docA, docB, docC], context); // Merge without merging nodes (keep separate) const mergedSeparate = await jsonld.merge([docA, docB, docC], null, { mergeNodes: false }); ``` -------------------------------- ### Process JSON-LD Context Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Resolves and processes a JSON-LD context, expanding terms and resolving remote references. This is useful for context validation and caching. It can process local or remote contexts, optionally using a custom document loader. ```javascript const jsonld = require('jsonld'); // Get initial empty context const initialCtx = await jsonld.processContext(null, null); // Process a local context const localCtx = { '@vocab': 'http://schema.org/', 'name': 'http://schema.org/name', 'Person': 'http://schema.org/Person' }; const activeCtx = await jsonld.processContext(initialCtx, localCtx); console.log('Context processed successfully'); // Process remote context const remoteCtx = await jsonld.processContext( initialCtx, 'https://schema.org', {documentLoader: customLoader} ); ``` -------------------------------- ### Frame JSON-LD Data Structure with jsonld.js Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt The `frame` method restructures JSON-LD data according to a specified template (frame). It allows for selective node and property inclusion, control over embedding depth, and shaping the output to meet application-specific requirements. Options like `embed`, `explicit`, `requireAll`, `omitDefault`, and `safe` can be used to customize the framing process. ```javascript const jsonld = require('jsonld'); const doc = { "@context": {"@vocab": "http://example.org/"}, "@graph": [ {"@id": "ex:library", "@type": "Library", "contains": {"@id": "ex:book1"}}, {"@id": "ex:book1", "@type": "Book", "title": "JSON-LD Guide", "author": {"@id": "ex:author1"}}, {"@id": "ex:author1", "@type": "Person", "name": "Jane Doe"} ] }; const frame = { "@context": {"@vocab": "http://example.org/"}, "@type": "Book" // Select all Book nodes }; const framed = await jsonld.frame(doc, frame); console.log(JSON.stringify(framed, null, 2)); /* Output: Document structured with Book as the root, author embedded */ // Frame with options const framedWithOptions = await jsonld.frame(doc, frame, { embed: '@once', explicit: false, requireAll: false, omitDefault: false, safe: true }); ``` -------------------------------- ### Flatten JSON-LD Document - Normalize Document Structure Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt The `flatten` method transforms a nested JSON-LD document into a flat array of nodes, where each node has an `@id` and references are managed via `@id`. This simplifies graph traversal and data processing. It can optionally apply a compaction context. ```javascript const jsonld = require('jsonld'); const doc = { "@context": { "name": "http://xmlns.com/foaf/0.1/name", "knows": "http://xmlns.com/foaf/0.1/knows" }, "@id": "http://example.org/alice", "name": "Alice", "knows": { "@id": "http://example.org/bob", "name": "Bob", "knows": { "@id": "http://example.org/carol", "name": "Carol" } } }; // Flatten without compaction const flattened = await jsonld.flatten(doc); console.log(JSON.stringify(flattened, null, 2)); /* Output: Array of flattened nodes with @id references */ // Flatten with compaction context const context = { "name": "http://xmlns.com/foaf/0.1/name", "knows": "http://xmlns.com/foaf/0.1/knows" }; const flattenedCompacted = await jsonld.flatten(doc, context); console.log(JSON.stringify(flattenedCompacted, null, 2)); /* Output: { "@context": {...}, "@graph": [ {"@id": "http://example.org/alice", "name": "Alice", "knows": {"@id": "http://example.org/bob"}}, {"@id": "http://example.org/bob", "name": "Bob", "knows": {"@id": "http://example.org/carol"}}, {"@id": "http://example.org/carol", "name": "Carol"} ] } */ ``` -------------------------------- ### Enable Safe Mode for JSON-LD Operations Source: https://context7.com/digitalbazaar/jsonld.js/llms.txt Safe mode causes processing to fail when data constructs are encountered that result in lossy behavior, ensuring data integrity. It is enabled by default for `canonize` and can be explicitly enabled for other operations like `expand`. ```javascript const jsonld = require('jsonld'); // Safe mode is enabled by default for canonize const canonized = await jsonld.canonize(doc); // safe: true by default // Enable safe mode for other operations const expanded = await jsonld.expand(doc, {safe: true}); // This will throw if lossy operations are detected try { const unsafeDoc = { "@id": "relative-id", // Relative IRI without base "undefinedTerm": "value" // Undefined term will be dropped }; await jsonld.expand(unsafeDoc, {safe: true}); } catch (e) { console.error('Safe mode error:', e.message); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.