jsonld.js

repository·main·Indexed 23 days ago

https://github.com/digitalbazaar/jsonld.js

A JavaScript implementation of the JSON-LD specification and API (version 9.0.1-0) designed to add semantics to JSON and enable Linked Data processing. The library provides core processing methods including compact, expand, flatten, frame, and canonize (URDNA2015), as well as utilities to serialize JSON-LD to RDF (toRDF) and deserialize RDF back into JSON-LD (fromRDF). It supports Node.js, modern browsers via ESM, and React Native with appropriate polyfills.

Tokens
3.4K
Snippets
14
Records
25
Agent score
83%

What's inside jsonld.js

  1. Enable Safe Mode for digital signing

    main

    When performing operations like canonize for digital signatures, you should use "safe mode" to prevent lossy behavior where data might be dropped. Enabling safe: true will cause processing to fail if such situations are detected.

    // expand a document in safe mode
    const expanded = await jsonld.expand(data, {safe: true});
    const expanded = await jsonld.expand(data, {safe: true});
  2. Use jsonld in the browser with bundles

    main

    The npm package includes pre-built bundles in the ./dist/ directory for browser use:

    • ./dist/jsonld.min.js: High compatibility version with polyfills for older browsers.
    • ./dist/jsonld.esm.min.js: Efficient version for modern browsers supporting ES Modules.

    You can use both simultaneously by using <script type="module"> for the ESM version and nomodule for the compatibility version.

    Alternatively, use a CDN:

    CDNJS:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jsonld/1.0.0/jsonld.min.js"></script>

    jsDeliver:

    <script src="https://cdn.jsdelivr.net/npm/jsonld@1.0.0/dist/jsonld.min.js"></script>

    unpkg:

    <script src="https://unpkg.com/jsonld@1.0.0/dist/jsonld.min.js"></script>
  3. Use jsonld.js with React Native

    main

    To use this library in React Native, you must import a polyfill like @digitalcredentials/data-integrity-rn before importing jsonld. The polyfill must provide crypto.subtle and TextEncoder.

    import '@digitalcredentials/data-integrity-rn'
    import * as jsonld from 'jsonld'
  4. Handle conversion warnings via eventHandler

    main

    The toRDF API uses an eventHandler to report issues that do not stop the conversion but result in data being skipped or modified. Common events include:

    • relative graph reference: A relative IRI was used as a graph name.
    • relative subject reference: A relative IRI was used as a subject.
    • relative predicate reference: A relative IRI was used as a predicate.
    • relative object reference: A relative IRI was used as an object.
    • blank node predicate: A blank node was used as a predicate (occurs if produceGeneralizedRdf is not true).
    • rdfDirection not set: The @direction keyword was used without a corresponding rdfDirection option.

    Event Object Structure:

    {
      "type": ["JsonLdEvent"],
      "code": "string_code",
      "level": "warning" | "error",
      "message": "Human readable message",
      "details": { "key": "value" }
    }
  5. Implement a custom Document Loader

    main

    You can override the default document loader to handle custom logic, such as using pre-loaded contexts instead of fetching them from the network.

    To set a global custom loader:

    // grab the built-in Node.js doc loader
    const nodeDocumentLoader = jsonld.documentLoaders.node();
    
    // define a custom loader
    const customLoader = async (url, options) => {
      if(url in CONTEXTS) {
        return {
          contextUrl: null,
          document: CONTEXTS[url],
          documentUrl: url
        };
      }
      return nodeDocumentLoader(url);
    };
    
    // change the default document loader
    jsonld.documentLoader = customLoader;

    Alternatively, pass a custom loader for a specific call:

    const compacted = await jsonld.compact(doc, context, {documentLoader: customLoader});
    const customLoader = async (url, options) => {
      if(url in CONTEXTS) {
        return {
          contextUrl: null,
          document: CONTEXTS[url],
          documentUrl: url
        };
      }
      return nodeDocumentLoader(url);
    };
    jsonld.documentLoader = customLoader;
  6. Register a custom RDF parser

    main

    You can extend the library by registering custom synchronous or promise-based RDF parsers for specific content types.

    // register a custom synchronous RDF parser
    jsonld.registerRDFParser(contentType, input => {
      // parse input to a jsonld.js RDF dataset object... and return it
      return dataset;
    });
    
    // register a custom promise-based RDF parser
    jsonld.registerRDFParser(contentType, async input => {
      // parse input into a jsonld.js RDF dataset object...
      return new Promise(...);
    });
    jsonld.registerRDFParser(contentType, input => {
      return dataset;
    });
  7. Deserialize from RDF (fromRDF)

    main

    The fromRDF method deserializes RDF data (like N-Quads) back into a JSON-LD document.

    // deserialize N-Quads (RDF) to JSON-LD
    const doc = await jsonld.fromRDF(nquads, {format: 'application/n-quads'});
    const doc = await jsonld.fromRDF(nquads, {format: 'application/n-quads'});
  8. Compact a JSON-LD document

    main

    The compact method reduces a JSON-LD document to a specific form based on a provided context. You can pass a context object or a URL.

    // compact a document according to a particular context
    const compacted = await jsonld.compact(doc, context);
    
    // compact using URLs
    const compacted = await jsonld.compact(
      'http://example.org/doc', 'http://example.org/context', ...
    );
    const compacted = await jsonld.compact(doc, context);