• Stars
    star
    1,629
  • Rank 28,066 (Top 0.6 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 13 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A JSON-LD Processor and API implementation in JavaScript

jsonld.js

Build status Coverage status npm

Introduction

This library is an implementation of the JSON-LD specification in JavaScript.

JSON, as specified in RFC7159, is a simple language for representing objects on the Web. Linked Data is a way of describing content across different documents or Web sites. Web resources are described using IRIs, and typically are dereferencable entities that may be used to find more information, creating a "Web of Knowledge". JSON-LD is intended to be a simple publishing method for expressing not only Linked Data in JSON, but for adding semantics to existing JSON.

JSON-LD is designed as a light-weight syntax that can be used to express Linked Data. It is primarily intended to be a way to express Linked Data in JavaScript and other Web-based programming environments. It is also useful when building interoperable Web Services and when storing Linked Data in JSON-based document storage engines. It is practical and designed to be as simple as possible, utilizing the large number of JSON parsers and existing code that is in use today. It is designed to be able to express key-value pairs, RDF data, RDFa data, Microformats data, and Microdata. That is, it supports every major Web-based structured data model in use today.

The syntax does not require many applications to change their JSON, but easily add meaning by adding context in a way that is either in-band or out-of-band. The syntax is designed to not disturb already deployed systems running on JSON, but provide a smooth migration path from JSON to JSON with added semantics. Finally, the format is intended to be fast to parse, fast to generate, stream-based and document-based processing compatible, and require a very small memory footprint in order to operate.

Conformance

This library aims to conform with the following:

The JSON-LD Working Group is now developing JSON-LD 1.1. Library updates to conform with newer specifications will happen as features stabilize and development time and resources permit.

The test runner is often updated to note or skip newer tests that are not yet supported.

Installation

Node.js + npm

npm install jsonld
const jsonld = require('jsonld');

Browser (bundler) + npm

npm install jsonld

Use your favorite bundling technology (webpack, Rollup, etc) to directly bundle your code that loads jsonld. Note that you will need support for ES2017+ code.

Browser Bundles

The built npm package includes bundled code suitable for use in browsers. Two versions are provided:

  • ./dist/jsonld.min.js: A version built for wide compatibility with modern and older browsers. Includes many polyfills and code transformations and is larger and less efficient.
  • ./dist/jsonld.esm.min.js: A version built for features available in browsers that support ES Modules. Fewer polyfills and transformations are required making the code smaller and more efficient.

The two bundles can be used at the same to to allow modern browsers to use newer code. Lookup using script tags with type="module" and nomodule.

Also see the webpack.config.js if you would like to make a custom bundle for specific targets.

Browser (AMD) + npm

npm install jsonld

Use your favorite technology to load node_modules/dist/jsonld.min.js.

CDNJS CDN

To use CDNJS include this script tag:

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

Check https://cdnjs.com/libraries/jsonld for the latest available version.

jsDeliver CDN

To use jsDeliver include this script tag:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jsonld.min.js"></script>

See https://www.jsdelivr.com/package/npm/jsonld for the latest available version.

unpkg CDN

To use unpkg include this script tag:

<script src="https://unpkg.com/[email protected]/dist/jsonld.min.js"></script>

See https://unpkg.com/jsonld/ for the latest available version.

JSPM

jspm install npm:jsonld
import * as jsonld from 'jsonld';
// or
import {promises} from 'jsonld';
// or
import {JsonLdProcessor} from 'jsonld';

Node.js native canonize bindings

For specialized use cases there is an optional rdf-canonize-native package available which provides a native implementation for canonize(). It is used by installing the package and setting the useNative option of canonize() to true. Before using this mode it is highly recommended to run benchmarks since the JavaScript implementation is often faster and the bindings add toolchain complexity.

npm install jsonld
npm install rdf-canonize-native

Examples

Example data and context used throughout examples below:

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"}
};

compact

// 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', ...);

expand

// 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', ...);

flatten

// flatten a document
const flattened = await jsonld.flatten(doc);
// output has all deep-level trees flattened to the top-level

frame

// frame a document
const framed = await jsonld.frame(doc, frame);
// output transformed into a particular tree structure per the given frame

canonize (normalize)

// 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.

toRDF (N-Quads)

// serialize a document to N-Quads (RDF)
const nquads = await jsonld.toRDF(doc, {format: 'application/n-quads'});
// nquads is a string of N-Quads

fromRDF (N-Quads)

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

Custom RDF Parser

// 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(...);
});

Custom Document Loader

// 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});

Node.js Document Loader User-Agent

It is recommended to set a default user-agent header for Node.js applications. The default for the default Node.js document loader is jsonld.js.

Safe Mode

A common use case is to avoid JSON-LD constructs that will result in lossy behavior. The JSON-LD specifications have notes about when data is dropped. This can be especially important when calling [canonize][] in order to digitally sign data. A special "safe mode" is available that will detect these situations and cause processing to fail.

Note: This mode is designed to be the common way that digital signing and similar applications use this library.

The safe options flag set to true enables this behavior:

// expand a document in safe mode
const expanded = await jsonld.expand(data, {safe: true});

Tests

This library includes a sample testing utility which may be used to verify that changes to the processor maintain the correct output.

The main test suites are included in external repositories. Check out each of the following:

https://github.com/w3c/json-ld-api
https://github.com/w3c/json-ld-framing
https://github.com/json-ld/json-ld.org
https://github.com/w3c/rdf-canon

They should be sibling directories of the jsonld.js directory or in a test-suites dir. To clone shallow copies into the test-suites dir you can use the following:

npm run fetch-test-suites

Node.js tests can be run with a simple command:

npm test

If you installed the test suites elsewhere, or wish to run other tests, use the TESTS environment var:

TESTS="/tmp/org/test-suites /tmp/norm/tests" npm test

This feature can be used to run the older json-ld.org test suite:

TESTS=/tmp/json-ld.org/test-suite npm test

Browser testing can be done with Karma:

npm run test-karma
npm run test-karma -- --browsers Firefox,Chrome

Code coverage of node tests can be generated in coverage/:

npm run coverage

To display a full coverage report on the console from coverage data:

npm run coverage-report

The Mocha output reporter can be changed to min, dot, list, nyan, etc:

REPORTER=dot npm test

Remote context tests are also available:

# run the context server in the background or another terminal
node tests/remote-context-server.js

TESTS=`pwd`/tests npm test

To generate EARL reports:

# generate the EARL report for Node.js
EARL=earl-node.jsonld npm test

# generate the EARL report for the browser
EARL=earl-firefox.jsonld npm run test-karma -- --browser Firefox

To generate an EARL report with the json-ld-api and json-ld-framing tests as used on the official JSON-LD Processor Conformance page

TESTS="`pwd`/../json-ld-api/tests `pwd`/../json-ld-framing/tests" EARL="jsonld-js-earl.jsonld" npm test

The EARL .jsonld output can be converted to .ttl using the rdf tool:

rdf serialize jsonld-js-earl.jsonld --output-format turtle -o jsonld-js-earl.ttl

Optionally follow the report instructions to generate the HTML report for inspection. Maintainers can submit updated results as needed.

Benchmarks

Benchmarks can be created from any manifest that the test system supports. Use a command line with a test suite and a benchmark flag:

TESTS=/tmp/benchmark-manifest.jsonld BENCHMARK=1 npm test

EARL reports with benchmark data can be generated with an optional environment details:

TESTS=`pwd`/../json-ld.org/benchmarks/b001-manifiest.jsonld BENCHMARK=1 EARL=earl-test.jsonld TEST_ENV=1 npm test

See tests/test.js for more TEST_ENV and BENCHMARK control and options.

These reports can be compared with the benchmarks/compare/ tool and at the JSON-LD Benchmarks site.

Related Modules

  • jsonld-cli: A command line interface tool called jsonld that exposes most of the basic jsonld.js API.
  • jsonld-request: A module that can read data from stdin, URLs, and files and in various formats and return JSON-LD.

Source

The source code for the JavaScript implementation of the JSON-LD API is available at:

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

Commercial Support

Commercial support for this library is available upon request from Digital Bazaar: [email protected]

More Repositories

1

forge

A native implementation of TLS in Javascript and tools to write crypto-based and network-heavy webapps
JavaScript
4,789
star
2

pyld

JSON-LD processor written in Python
Python
581
star
3

php-json-ld

PHP implementation of a JSON-LD Processor and API
PHP
266
star
4

vc

W3C Verifiable Credentials implementation in JavaScript
JavaScript
138
star
5

jsonld-signatures

An implementation of the Linked Data Signatures specification for JSON-LD. Works in the browser and Node.js.
JavaScript
132
star
6

bedrock

Bedrock: A core foundation for rich Web applications.
JavaScript
59
star
7

did-cli

A client for managing Decentralized Identifiers
JavaScript
44
star
8

authn.io

Credential Mediator Polyfill
Vue
43
star
9

monarch

The Modular Networking Architecture - high-performance libraries for creating REST-based, JSON Web Services
C++
43
star
10

did-io

Decentralized identifier management library for browser and node.js
JavaScript
40
star
11

jsonld-request

LIbrary to load JSON-LD from stdin, URLs, or files.
JavaScript
38
star
12

crypto-ld

JavaScript
31
star
13

jsonld-cli

JSON-LD command line interface tool
JavaScript
31
star
14

json-ld

A Context-based JSON Serialization for Linked Data
Perl
25
star
15

credential-handler-polyfill

Credential Handler API polyfill
JavaScript
24
star
16

zcap

Linked Data Capabilities reference implementation
JavaScript
23
star
17

did-method-key

A did-io driver for the DID "key" method
JavaScript
23
star
18

payswarm-wordpress

PaySwarm plugin for WordPress
CSS
18
star
19

payswarm.js

A PaySwarm client for node.js
JavaScript
18
star
20

qram

Cram arbitrarily large data into multiple streaming QR-codes
JavaScript
18
star
21

rdf-canonize

An implementation of the RDF Dataset Normalization Algorithm in JavaScript.
JavaScript
15
star
22

hashlink

JavaScript implementation of Cryptographic Hyperlinks specification.
JavaScript
13
star
23

minimal-cipher

Minimal encryption/decryption JWE library, secure algs only, browser-compatible.
JavaScript
13
star
24

cborld

A Javascript CBOR-LD processor for web browsers and Node.js apps.
JavaScript
13
star
25

p3

The PaySwarm Payment Processor (p3)
JavaScript
12
star
26

edv-client

An Encrypted Data Vault Client
JavaScript
11
star
27

encrypted-data-vaults

A privacy-respecting mechanism for storing, indexing, and retrieving encrypted data at a storage provider.
HTML
10
star
28

vc-revocation-list

Verifiable Credentials Revocation List 2020 JavaScript implementation
JavaScript
10
star
29

payswarm

The PaySwarm Project is creating a standard mechanism for purchasing and re-selling digital goods online.
Python
10
star
30

ed25519-signature-2020

Ed25519Signature2020 Linked Data Proof suite for use with jsonld-signatures.
JavaScript
9
star
31

payswarm-python

Python client library for PaySwarm
Python
9
star
32

equihash

Equihash Proof of Work for Node.js
C++
9
star
33

opencred-idp

Open Credentials Identity Provider and demo websites
PHP
8
star
34

http-signature-header

JavaScript
8
star
35

vc-demo

A demonstration of issuing and verifying Verifiable Credentials.
8
star
36

forge-dist

A native JavaScript implementation of TLS, cryptography primitives, and other webapp tools.
7
star
37

bitmunk

An open source, copyright-aware peer-to-peer client that enables browser-based buying/selling of music, movies and television by fans.
C++
7
star
38

cc-structured-data

Analyzes HTML content for RDFa, Microdata and Microformats
Java
6
star
39

credential-handler-demo

Credential Handler API demo
Vue
6
star
40

rdf-canonize-native

A native implementation of the RDF Dataset Normalization Algorithm for Node.js.
JavaScript
6
star
41

ezcap

An opinionated Authorization Capabilities client
JavaScript
6
star
42

webkms-client

A JavaScript Web Kms client library
JavaScript
6
star
43

le-store-redis

Redis certificate storage back-end for Node Let's Encrypt
JavaScript
5
star
44

bedrock-ledger-storage-mongodb

A storage subsystem for Bedrock ledger.
JavaScript
5
star
45

web-ledger-client

An implementation of a a Web Ledger client
JavaScript
5
star
46

ed25519-verification-key-2018

Javascript library for generating and working with Ed25519 key pairs, for use with crypto-ld.
JavaScript
5
star
47

jsonld-document-loader

JavaScript
5
star
48

web-payments.io

Website-side of the payments polyfill
JavaScript
5
star
49

webid-demo

WebID demonstration source code
JavaScript
5
star
50

jsonld-patch

JSON patch for JSON-LD
JavaScript
5
star
51

base58-universal

Encode/decode using "The Base58 Encoding Scheme".
JavaScript
4
star
52

payment-handler-polyfill

A polyfill for the Payment Handler API
JavaScript
4
star
53

opencred-verifier

Open Credentials Verifier JavaScript API
JavaScript
4
star
54

vpqr

Takes a Verifiable Presentation, compresses it via CBOR-LD, and turns it into a QR Code. For Node.js and browser.
JavaScript
4
star
55

bedrock-ledger-node

A Bedrock module that supports the creation and management of decentralized ledgers.
JavaScript
4
star
56

base64url-universal

Encode/decode "Base64url Encoding" format of JSON Web Signature (JWS) RFC7517.
JavaScript
4
star
57

did-context

DID Context
JavaScript
4
star
58

x25519-key-agreement-key-2019

An X25519 (Curve25519) DH key implementation to work with the crypto-ld LDKeyPair API
JavaScript
4
star
59

http-signature-zcap-invoke

A library for invoking Authorization Capabilities via HTTP signatures
JavaScript
3
star
60

web-request-mediator

A mediator for requests made by relying party Web Apps that are fulfilled by third party service provider Web apps
JavaScript
3
star
61

bedrock-edv-storage

Encrypted Data Vault Storage for Bedrock Apps
JavaScript
3
star
62

ed25519-signature-2018

A Javascript Ed25519 signature suite, for use with jsonld-signatures in the browser and server-side.
JavaScript
3
star
63

bitstring

A Bitstring module for universal JavaScript
JavaScript
3
star
64

bedrock-ledger-consensus-continuity

Web Ledger Continuity Consensus Protocol
JavaScript
3
star
65

security-document-loader

A JSON-LD documentLoader library pre-loaded with core commonly used contexts (suites, VC, DIDs).
JavaScript
3
star
66

monarch-benchmark

A suite of tools for benchmarking Monarch and Apache
C++
2
star
67

bedrock-angular-lazy-compile

Bedrock AngularJS Lazy Compile
JavaScript
2
star
68

bedrock-web-vc-store

A Javascript library for storing Verifiable Credentials for Bedrock web apps
JavaScript
2
star
69

payment-handler-demo

Payment Handler API polyfill demo
HTML
2
star
70

base58-spec

The Base58 Encoding Scheme
XSLT
2
star
71

bedrock-angular-form

Bedrock AngularJS Form support
JavaScript
2
star
72

web-request-rpc

JSON-RPC for Web Request Polyfills
JavaScript
2
star
73

bedrock-kms-http

HTTP APIs for Bedrock Key Management
JavaScript
2
star
74

eslint-config-digitalbazaar

JavaScript
2
star
75

canivc

Community compatibility dashboard for the Verifiable Credential ecosystem.
JavaScript
2
star
76

obv3-test-suite

Open Badges v3 Test Suite
JavaScript
2
star
77

bedrock-idp

Bedrock Identity Provider
JavaScript
2
star
78

payswarm-news-demo

Demonstration of a PaySwarm Token application for bloggers and journalists
JavaScript
2
star
79

bedrock-account-http

HTTP APIs for Bedrock User Accounts
JavaScript
2
star
80

ed25519-verification-key-2020

Javascript library for generating and working with Ed25519VerificationKey2020 key pairs, for use with crypto-ld.
JavaScript
2
star
81

did-ssh

2
star
82

bedrock-mongodb

Bedrock mongodb module
JavaScript
2
star
83

vc-js-cli

JavaScript
2
star
84

ecdsa-secp256k1-verification-key-2019

JavaScript
2
star
85

http-client

An opinionated, isomorphic HTTP client.
JavaScript
2
star
86

bedrock-vue

Vue frontend framework running on Bedrock
JavaScript
2
star
87

chapi-demo-wallet

Credential Handler API Demo Wallet
HTML
2
star
88

bedrock-tokenization

A Bedrock module for tokenizing identifiers and storing encrypted related data
JavaScript
2
star
89

webkms-switch

A JavaScript Web Kms switch library
JavaScript
2
star
90

bedrock-views

Bedrock website views module
JavaScript
1
star
91

bedrock-authn-token

Simple token-based authentication for Bedrock apps
JavaScript
1
star
92

d-langtag-ext

An extension to the language tag to support text direction.
XSLT
1
star
93

edv

Encrypted Data Vault
1
star
94

did-method-key-spec

HTML
1
star
95

bedrock-ledger-agent

Bedrock module that provides management of ledger agents
JavaScript
1
star
96

http-proofs

A new HTTP Header to express cryptographic proofs, such as proof-of-work, when accessing a resource.
XSLT
1
star
97

bedrock-web-pdf417

JavaScript
1
star
98

bedrock-mail

Bedrock mail
JavaScript
1
star
99

cit-vocab

Concealed ID Tokens
HTML
1
star
100

bedrock-ldn-receiver

Bedrock module for Linked Data Notification Receiver
JavaScript
1
star