项目作者: rubensworks

项目描述 :
Parses JSON-LD contexts
高级语言: TypeScript
项目地址: git://github.com/rubensworks/jsonld-context-parser.js.git
创建时间: 2018-07-24T13:07:49Z
项目社区:https://github.com/rubensworks/jsonld-context-parser.js

开源协议:MIT License

下载


JSON-LD Context Parser

Build status
Coverage Status
npm version

A JSON-LD @context parser that will normalize these contexts so that they can easily be used in your application.

This parser has the following functionality:

  • Fetch contexts by URLs.
  • Normalize JSON contexts.
  • Merge arrays of contexts.
  • Create a default @base entry if a base IRI is provided.
  • Create @id entries for all @reverse occurences.
  • Convert @container string and array values to a hash-based value.
  • Expand prefixes and @vocab in string values, @id, @type and @reverse.
  • Context validation according to the JSON-LD specification while parsing (can be disabled).
  • Term expansion with the context.expandTerm.
  • IRI compacting with the context.compactIri.

Example input (with base IRI set to http://example.org/base):

  1. [
  2. {
  3. "@vocab": "http://vocab.org/",
  4. "npmd": "https://linkedsoftwaredependencies.org/bundles/npm/",
  5. "p": { "@id": "pred1", "@language": "nl" }
  6. },
  7. "http://example.org/simple.jsonld",
  8. ]

With http://example.org/simple.jsonld containing:

  1. {
  2. "xsd": "http://www.w3.org/2001/XMLSchema#",
  3. "name": "http://xmlns.com/foaf/0.1/name"
  4. }

Example output:

  1. {
  2. "@base": "http://example.org/base",
  3. "@vocab": "http://vocab.org/",
  4. "npmd": "https://linkedsoftwaredependencies.org/bundles/npm/",
  5. "p": { "@id": "http://vocab.org/pred1", "@language": "nl" },
  6. "xsd": "http://www.w3.org/2001/XMLSchema#",
  7. "name": "http://xmlns.com/foaf/0.1/name"
  8. },

Install

This package can be installed via npm.

  1. $ npm install jsonld-context-parser

This package also works out-of-the-box in browsers via tools such as webpack and browserify.

Usage

API

Create a new parser

  1. const ContextParser = require('jsonld-context-parser').ContextParser;
  2. const myParser = new ContextParser();

Optionally, the following constructor options can be passed:

  • documentLoader: An optional document loader that should be used for fetching external JSON-LD contexts. Custom loaders must implement the IDocumentLoader interface (Default: new FetchDocumentLoader())
  • skipValidation: By default, JSON-LD contexts will be validated. This can be disabled by setting this option to true. (Default: false)
  • expandContentTypeToBase: If @type inside the context may be expanded via @base is @vocab is set to null. (Default: false)
  • remoteContextsDepthLimit: The maximum number of remote contexts that can be fetched recursively. (Default: 32)
  1. const myParser = new ContextParser({
  2. documentLoader: new FetchDocumentLoader(),
  3. skipValidation: true,
  4. expandContentTypeToBase: true,
  5. });

Parse a context.

Either parse a context by URL:

  1. const myContext = await myParser.parse('http://json-ld.org/contexts/person.jsonld');

by an non-normalized context:

  1. const myContext = await myParser.parse({ ... });

or by an array of mixed contexts or URLs:

  1. const myContext = await myParser.parse([
  2. 'http://json-ld.org/contexts/person.jsonld',
  3. { ... },
  4. 'https://linkedsoftwaredependencies.org/contexts/components.jsonld'
  5. ]);

Optionally, the following parsing options can be passed:

  • baseIRI: An initial default base IRI. (Default: '')
  • parentContext: An optional context to inherit from. (Default: null)
  • external: If the given context is being loaded from an external URL. (Default: false)
  • processingMode: The JSON-LD version that the context should be parsed with. (Default: 1.1)
  • normalizeLanguageTags: Whether or not language tags should be normalized to lowercase. (Default: false for JSON-LD 1.1 (and higher), true for JSON-LD 1.0)
  • ignoreProtection: If checks for validating term protection should be skipped. (Default: false)
  • minimalProcessing: If the context should only be parsed and validated, without performing normalizations and other modifications. (Default: false)
  • ignoreRemoteScopedContexts: If true, a remote context that will be looked up, and is already contained in remoteContexts, will not emit an error but will produce an empty context. (Default: false)
  • remoteContexts: A hash containing all remote contexts that have been looked up before. (Default: false)
  1. const myContext = await myParser.parse({ ... }, {
  2. baseIRI: 'http://example.org/',
  3. parentContext: {},
  4. external: true,
  5. processingMode: 1.0,
  6. normalizeLanguageTags: true,
  7. ignoreProtection: true,
  8. minimalProcessing: true,
  9. ignoreRemoteScopedContexts: true,
  10. remoteContexts: {
  11. 'http://example.org/context.json': true,
  12. }
  13. });

Expand a term

Based on a context, terms can be expanded in vocab or base-mode.

Base expansion

Base expansion is done based on the @base context entry.
This should typically be used for expanding terms in the subject or object position.

  1. // Expands `person` based on the @base IRI. Will throw an error if the final IRI is invalid.
  2. myContext.expandTerm('person');
  3. // Expands if `foaf` is present in the context
  4. myContext.expandTerm('foaf:name');
  5. // Returns the URI as-is
  6. myContext.expandTerm('http://xmlns.com/foaf/0.1/name');
Vocab expansion

Vocab expansion is done based on the @vocab context entry.
This should typically be used for expanding terms in the predicate position.

  1. // Expands `name` based on the @vocab IRI.
  2. myContext.expandTerm('name', true);
  3. // Expands if `foaf` is present in the context
  4. myContext.expandTerm('foaf:name', true);
  5. // Returns the URI as-is
  6. myContext.expandTerm('http://xmlns.com/foaf/0.1/name', true);
Expansion options

Optionally, the following options can be passed for expansion:

  • allowPrefixNonGenDelims: If compact IRI prefixes can end with any kind of character in simple term definitions, instead of only the default gen-delim characters (:,/,?,#,[,],@). (Default: false)
  • allowPrefixForcing: If compact IRI prefixes ending with a non-gen-delim character can be forced as a prefix using @prefix: true. (Default: false)
  • allowVocabRelativeToBase: If @vocab values are allowed contain IRIs relative to @base. (Default: true)
  1. myContext.expandTerm('person', false, {
  2. allowPrefixNonGenDelims: false,
  3. allowPrefixForcing: false,
  4. allowVocabRelativeToBase: true,
  5. });

The defaultExpandOptions variable that is exported from this package contains the default expansion options hash.

Compact an IRI

Based on a context, IRIs can be compacted in vocab or base-mode.

Base compacting

Base compacting is done based on the @base context entry.
This should typically be used for compacting terms in the subject or object position.

  1. // Compacts to `something` if @base is `http://base.org/`.
  2. myContext.compactIri('http://base.org/something');
  3. // Compacts to `prefix:name` if `"prefix": "http://prefix.org/"` is in the context
  4. myContext.compactIri('http://prefix.org/name');
  5. // Returns the URI as-is if it is not present in the context in any way
  6. myContext.compactIri('http://xmlns.com/foaf/0.1/name');
Vocab compacting

Vocab compacting is done based on the @vocab context entry.
This should typically be used for compacting terms in the predicate position.

  1. // Compacts to `something` if @vocab is `http://vocab.org/`.
  2. myContext.compactIri('http://vocab.org/something', true);
  3. // Compacts to `prefix:name` if `"prefix": "http://prefix.org/"` is in the context
  4. myContext.compactIri('http://prefix.org/name', true);
  5. // Compacts to `term` if `"term": "http://term.org/"` is in the context
  6. myContext.compactIri('http://term.org/', true);
  7. // Returns the URI as-is if it is not present in the context in any way
  8. myContext.compactIri('http://xmlns.com/foaf/0.1/name', true);

Getting the raw normalized context

The output of ContextParser#parse is a JsonLdContextNormalized object
that represents the normalized context and exposes convenience functions such as expandTerm and compactIri.

In some cases, you may want to store the raw normalized JSON-LD context, e.g. caching to a file.
For this, you can invoke the JsonLdContextNormalized#getContextRaw function as follows:

  1. const myContext = await myParser.parse('http://json-ld.org/contexts/person.jsonld');
  2. const myRawJsonLdContext = myContext.getContextRaw();

Afterwards, you can load this raw context into a new JsonLdContextNormalized context:

  1. const JsonLdContextNormalized = require('jsonld-context-parser').JsonLdContextNormalized;
  2. const myNewContext = new JsonLdContextNormalized(myRawJsonLdContext);
  3. // Call functions such as myNewContext.expandTerm(...)

Advanced

This library exposes many operations that are useful to parse and handle a JSON-LD context.
For this, the static functions on Util
and ContextParser can be used.

Command-line

A command-line tool is provided to quickly normalize any context by URL, file or string.

Usage:

  1. $ jsonld-context-parse url http://json-ld.org/contexts/person.jsonld
  2. $ jsonld-context-parse file path/to/context.jsonld
  3. $ jsonld-context-parse arg '{ "xsd": "http://www.w3.org/2001/XMLSchema#" }'

License

This software is written by Ruben Taelman.

This code is released under the MIT license.