W3C

JSON-LD API Algorithms 1.0

An Application Programming Interface Algorithms for the Processing JSON-LD Syntax Documents

W3C Editor's Draft 30 September 25 December 2012

This version:
http://dvcs.w3.org/hg/json-ld/raw-file/default/spec/latest/json-ld-api/index.html
Latest published version:
http://www.w3.org/TR/json-ld-api/
Latest editor's draft:
http://dvcs.w3.org/hg/json-ld/raw-file/default/spec/latest/json-ld-api/index.html
Editors:
Manu Sporny , Digital Bazaar
Gregg Kellogg , Kellogg Associates
Markus Lanthaler , Graz University of Technology
Authors:
Dave Longley , Digital Bazaar
Manu Sporny , Digital Bazaar
Gregg Kellogg , Kellogg Associates
Markus Lanthaler , Graz University of Technology

This document is also available in this non-normative format: diff to previous version


Abstract

JSON [ RFC4627 ] has proven to be a highly useful object serialization and messaging format. JSON-LD [ JSON-LD ] harmonizes the representation of Linked Data in JSON by outlining a common JSON representation format for expressing directed graphs; mixing both Linked Data and non-Linked Data in a single document. This document outlines an Application Programming Interface and a set of algorithms for programmatically transforming JSON-LD documents in order to make them easier to work with in programming environments like JavaScript, Python, and Ruby.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document has been under development for over 18 months in the JSON for Linking Data Community Group. The document has recently been transferred to the RDF Working Group for review, improvement, and publication along the Recommendation track. The specification has undergone significant development, review, and changes during the course of the last 18 months.

There are currently several independent five interoperable implementations of this specification. There is a fairly complete test suite and a live JSON-LD editor that is capable of demonstrating the features described in this document. While development on implementations, the test suite and the live editor will continue, they are believed to be mature enough to be integrated into a non-production system at this point in time with the expectation that they could be used in a production system within the next year.

Issue

It is important for readers to understand that the scope of this document is currently under debate and new features may be added to the specification. Existing features may be modified heavily or removed entirely from the specification upon further review and feedback from the broader community. This is a work in progress and publication as a Working Draft does not require that all Working Group members agree on the content of the document.

There are a number of ways that one may participate in the development of this specification:

This document was published by the RDF Working Group as an Editor's Draft. If you wish to make comments regarding this document, please send them to public-rdf-comments@w3.org ( subscribe , archives ). All feedback is welcome.

Publication as an Editor's Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy . W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy .

Table of Contents

1. Introduction

This section is non-normative.

This document is a detailed specification for an Application Programming Interface for the JSON-LD Syntax. The document is primarily intended for the following audiences:

To understand the basics in this specification you must first be familiar with JSON, which is detailed in [ RFC4627 ]. You must also understand the JSON-LD Syntax [ JSON-LD ], which is the base syntax used by all of the algorithms in this document. To understand the API and how it is intended to operate in a programming environment, it is useful to have working knowledge of the JavaScript programming language [ ECMA-262 ] and WebIDL [ WEBIDL ]. To understand how JSON-LD maps to RDF, it is helpful to be familiar with the basic RDF concepts [ RDF-CONCEPTS ].

2. Features

This section is non-normative.

The JSON-LD Syntax specification [ JSON-LD ] outlines a language that may be used to express Linked Data in JSON. Often, it is useful to be able to transform JSON-LD documents so that they may be easily processed in a various programming environment like JavaScript, Python or Ruby. environments.

There are four major types of transformation that are discussed in this document; compaction, document: expansion, compaction, flattening, and RDF conversion.

2.1 Expansion

This section is non-normative.

Software algorithms are easiest to write when the data that they are processing have a regular form. Since information can be represented by JSON-LD in a variety of different ways, transforming all of these methods into a uniform structure allows the developer to simplify their processing code. For example, note that the following input uses only term s and is fairly compact:

var input1 = { "@context": "http://json-ld.org/contexts/person.jsonld" "name": "Manu Sporny", "homepage": "http://manu.sporny.org/"
Example 1
{
  "@context": {
    "name": "http://xmlns.com/foaf/0.1/name",
    "homepage": {
      "@id": "http://xmlns.com/foaf/0.1/homepage",
      "@type": "@id"
    }
  },
  "@id": "http://me.markus-lanthaler.com/",
  "name": "Markus Lanthaler",
  "homepage": "http://www.markus-lanthaler.com/"

}

The next input example uses one IRI to express a property, but leaves the rest of the information untouched.

var input2 = { "@context": "http://json-ld.org/contexts/person.jsonld" "": "Manu Sporny", "homepage": "http://manu.sporny.org/"
Example 2
{
  "@context": {
    "homepage": {
      "@id": "http://xmlns.com/foaf/0.1/homepage",
      "@type": "@id"
    }
  },
  "@id": "http://me.markus-lanthaler.com/",
  "http://xmlns.com/foaf/0.1/name": "Markus Lanthaler",
  "homepage": "http://www.markus-lanthaler.com/"

}

While both inputs are valid JSON-LD, writing a program to handle every permutation of possible inputs can be difficult, especially when the incoming context could change as well. To ensure that the data can be given a more uniform structure, JSON-LD introduces the notion of expansion. Expansion performs two important operations. The first is to expand all values that are represent IRI IRIs s to their fully expanded form. absolute IRIs . The second is to express all values in expanded form . To transform both inputs above to the same representation, . Running the developer could do Expansion algorithm against the following: function expansionCallback(output) { console.log(output); } // the second parameter is 'null' because the developer does not wish to // inject another context value jsonld.expand(input1, null, expansionCallback); jsonld.expand(input2, null, expansionCallback); The output for both calls examples provided above will be: results in the following output:

[{ "http://xmlns.com/foaf/0.1/name": [{ "@value": "Manu Sporny" }], "http://xmlns.com/foaf/0.1/homepage": [{ "@id": "http://manu.sporny.org/" }] }]
Example 3
[
  {
    "@id": "http://me.markus-lanthaler.com/",
    "http://xmlns.com/foaf/0.1/name": [
      { "@value": "Markus Lanthaler" }
    ],
    "http://xmlns.com/foaf/0.1/homepage": [
      { "@id": "http://www.markus-lanthaler.com/" }
    ]
  }
]

Note that in the example above; output above all context definitions have been removed, all term terms and prefixes have been expanded to full IRIs, absolute IRIs , and all literal JSON-LD values s are expressed in expanded form . While the output is more difficult for a human to read, it is easier for a software program to process because of its very regular structure.

2.2 Compaction

This section is non-normative.

While expansion expands a given input as much as possible, compaction performs the opposite operation - expressing operation: it expresses a given input as succinctly as possible. While In contrast to expansion which is meant to produce something that is easy to process by software programs, compaction is meant to produce something that is easy to read by software developers. Compaction uses a developer-supplied context to compresses all compress IRI IRIs s to term terms s or prefix compact IRIs es, and compacts all literal JSON-LD values s expressed in expanded form to simple values such as much as possible. strings and numbers .

The For example, assume the following example expresses expanded JSON-LD input that has already been fully expanded: document:

var expandedInput = [{ "http://xmlns.com/foaf/0.1/name": [{ "@value": "Manu Sporny" }], "http://xmlns.com/foaf/0.1/homepage": [{ "@id": "http://manu.sporny.org/" }] }]
Example 4
[
  {
    "@id": "http://me.markus-lanthaler.com/",
    "http://xmlns.com/foaf/0.1/name": [
      { "@value": "Markus Lanthaler" }
    ],
    "http://xmlns.com/foaf/0.1/homepage": [
      { "@id": "http://www.markus-lanthaler.com/" }
    ]
  }
]

A developer that wants to transform the data above into a more human-readable form, could do Additionally, assume the following using the developer-supplied JSON-LD API: context :

function compactionCallback(output) { console.log(output);
Example 5
{
  "@context": {
    "name": "http://xmlns.com/foaf/0.1/name",
    "homepage": {
      "@id": "http://xmlns.com/foaf/0.1/homepage",
      "@type": "@id"
    }
  }

}
jsonld.compact(expandedInput,
"http://json-ld.org/contexts/person.jsonld",
compactionCallback);

The following would be Running the Compaction Algorithm given the context supplied above against the JSON-LD input document provided above would result of in the call above: following output:

{ "@context": "http://json-ld.org/contexts/person.jsonld" "name": "Manu Sporny", "homepage": "http://manu.sporny.org/"
Example 6
{
  "@context": {
    "name": "http://xmlns.com/foaf/0.1/name",
    "homepage": {
      "@id": "http://xmlns.com/foaf/0.1/homepage",
      "@type": "@id"
    }
  },
  "@id": "http://me.markus-lanthaler.com/",
  "name": "Markus Lanthaler",
  "homepage": "http://www.markus-lanthaler.com/"

}

Note that all of the term IRIs s have been compressed and compacted to terms as specified in the context which consequently has been injected into the output. While compacted output is most useful to humans, it can often also be carefully used to generate structures that are easy to use for program against. Compaction enables developers to program against as well. map any expanded document into an application-specific compacted document. While the context provided above mapped http://xmlns.com/foaf/0.1/name to name , it could have also have been mapped to any other term provided by the developer.

2.3 Flattening

This section is non-normative.

While expansion ensures that a document is in a uniform structure, flattening goes a step further and ensures that also the shape of the data is deterministic. In expanded documents properties of a single node may still be spread across a number of different JSON objects . By flattening a document, all properties of a node are collected in a single JSON object and all blank nodes are labeled with a blank node identifier . Often this drastically simplifies the code to process JSON-LD data.

For example, assume the following JSON-LD input document:

Example 7
{
  "@context": {
    "name": "http://xmlns.com/foaf/0.1/name",
    "knows": "http://xmlns.com/foaf/0.1/knows"
  },
  "@id": "http://me.markus-lanthaler.com/",
  "name": "Markus Lanthaler",
  "knows": [
    {
      "name": "Manu Sporny",
      "knows": {
        "@id": "http://greggkellogg.net/foaf#me"
      }
    },
    {
      "@id": "http://greggkellogg.net/foaf#me",
      "name": "Gregg Kellogg"
    }
  ]
}

Running the Flattening Algorithm with a context set to null to prevent compaction returns the following document:

Example 8
[
  {
    "@id": "http://me.markus-lanthaler.com/",
    "http://xmlns.com/foaf/0.1/name": [
      { "@value": "Markus Lanthaler" }
    ],
    "http://xmlns.com/foaf/0.1/knows": [
      { "@id": "_:t0" },
      { "@id": "http://greggkellogg.net/foaf#me" }
    ]
  },
  {
    "@id": "_:t0",
    "http://xmlns.com/foaf/0.1/name": [
      { "@value": "Manu Sporny" }
    ],
    "http://xmlns.com/foaf/0.1/knows": [
      { "@id": "http://greggkellogg.net/foaf#me" }
    ]
  },
  {
    "@id": "http://greggkellogg.net/foaf#me",
    "http://xmlns.com/foaf/0.1/name": [
      { "@value": "Gregg Kellogg" }
    ]
  }
]

Note how in the output above all properties of a node are collected in a single JSON object and how the blank node representing "Manu Sporny" has been assigned the blank node identifier _:t0 .

To make it easier for humans to read such a flattened document can be compacted by passing a context. Using the same context as the input document, the flattened and compacted document looks as follows:

Example 9
{
  "@context": {
    "name": "http://xmlns.com/foaf/0.1/name",
    "knows": "http://xmlns.com/foaf/0.1/knows"
  },
  "@graph": [
    {
      "@id": "http://me.markus-lanthaler.com/",
      "name": "Markus Lanthaler",
      "knows": [
        { "@id": "_:t0" },
        { "@id": "http://greggkellogg.net/foaf#me" }
      ]
    },
    {
      "@id": "_:t0",
      "name": "Manu Sporny",
      "knows": {
        "@id": "http://greggkellogg.net/foaf#me"
      }
    },
    {
      "@id": "http://greggkellogg.net/foaf#me",
      "name": "Gregg Kellogg"
    }
  ]
}

Please note that the flattened and compacted result will always explicitly designate the default by the @graph member in the top-level JSON object . Compaction optimizes that member away if its value contains just one item.

2.4 RDF Conversion

This section is non-normative.

JSON-LD can be used to losslessly express the RDF serialize data model expressed in RDF as described in the RDF Concepts document [ RDF-CONCEPTS ]. This ensures that data can be round-tripped from and to any RDF syntax, like N-Triples or TURTLE, syntax without any loss in the fidelity of the data. Assume

For example, assume the following RDF input serialized in N-Triples format: Turtle [ TURTLE-TR ]:

var data = " <http://manu.sporny.org/about/#manu> <http://xmlns.com/foaf/0.1/name> \"Manu Sporny\" .\n <http://manu.sporny.org/about/#manu>
Example 10
<http://me.markus-lanthaler.com/> <http://xmlns.com/foaf/0.1/name> "Markus Lanthaler" .
<http://me.markus-lanthaler.com/>

<http://xmlns.com/foaf/0.1/homepage>
<http://manu.sporny.org/>
.";

<http://www.markus-lanthaler.com/>
.

A developer can use Using the JSON-LD API to Convert from RDF Algorithm a developer could transform the markup above this document into a JSON-LD document: function conversionCallback(result) { console.log("JSON-LD Document: ", result); }; jsonld.fromRDF(data, conversionCallback, {"format": "ntriples"}); The following expanded output would be the result of the call above: JSON-LD:

[{ "@id": "http://manu.sporny.org/about/#manu", "http://xmlns.com/foaf/0.1/name": [{ "@value": "Manu Sporny" }], "http://xmlns.com/foaf/0.1/homepage": [{ "@id": "http://manu.sporny.org/" }] }]
Example 11
[
  {
    "@id": "http://me.markus-lanthaler.com/",
    "http://xmlns.com/foaf/0.1/name": [
      {
        "@value": "Markus Lanthaler"
      }
    ],
    "http://xmlns.com/foaf/0.1/homepage": [
      {
        "@id": "http://www.markus-lanthaler.com/"
      }
    ]
  }
]

Note that the output above, above could easily be compacted to produce the following using the technique outlined in the previous section: { "@context": "http://json-ld.org/contexts/person.jsonld", "@id": "http://manu.sporny.org/about/#manu", "name": "Manu Sporny", "homepage": "http://manu.sporny.org/" } Transforming section. It is also possible to transform the node above JSON-LD document back to RDF is as simple as calling using the toRDF() method: Convert to RDF Algorithm .

var jsonldDocument = ...; // assign the JSON-LD document here function rdfCallback(quads) { console.log("RDF Data: ", quads); }; jsonld.toRDF(jsonldDocument, rdfCallback);

3. The Application Programming Interface Conformance

This API provides a clean mechanism All examples and notes as well as sections marked as non-normative in this specification are non-normative. Everything else in this specification is normative.

The keywords must , must not , required , should , should not , recommended , may , and optional in this specification are to be interpreted as described in [ RFC2119 ].

There are two classes of products that enables developers can claim conformance to convert this specification: JSON-LD data into a Implementations and JSON-LD Processors .

A conforming JSON-LD Implementation is a variety system capable of output formats that are easier to work with transforming JSON-LD documents according the algorithms defined in various programming languages. If a this specification.

A conforming JSON-LD API Processor is provided in a conforming JSON-LD Implementation that exposes the application programming environment, interface (API) defined in this specification.

The algorithms in this specification are generally written with more concern for clarity than over efficiency. Thus, JSON-LD Implementations and Processors may implement the entirety of algorithms given in this specification in any way desired, so long as the following API end result is indistinguishable from the result that would be obtained by the specification's algorithms.

This specification does not define how JSON-LD Implementations or Processors handle non-conforming input documents. This implies that JSON-LD Implementations or Processors must not be implemented. attempt to correct malformed IRIs or language tags; however, they may issue validation warnings.

3.1 General Terminology
Issue Note

The intent of the Working Group and the Editors Implementers can partially check their level of this specification is conformance to eventually align terminology used in this document with specification by successfully passing the terminology used in test cases of the RDF Concepts document to JSON-LD test suite [ JSON-LD-TESTS ]. Note, however, that passing all the extent to which it makes sense to do so. In general, if there is an analogue to terminology used in this document tests in the RDF Concepts document, the preference is test suite does not imply complete conformance to use this specification. It only implies that the terminology in implementation conforms to aspects tested by the RDF Concepts document. test suite.

4. General Terminology

The This document uses the following is an explanation of terms as defined in JSON [ RFC4627 ]. Refer to the general terminology used JSON Grammar section in this document: [ RFC4627 ] for formal definitions.

JSON object
An object structure is represented as a pair of curly brackets surrounding zero or more name-value key-value pairs. A name key is a string . A single colon comes after each name, key, separating the name key from the value. A single comma separates a value from a following name. The names within an object should be unique. key.
array
An array structure is represented as square brackets surrounding zero or more values that (or elements). Elements are separated by commas. In JSON, an array is an ordered sequence of zero or more values. While JSON-LD uses the same array representation as JSON, the collection is unordered by default. While order is preserved in regular JSON arrays, it is not in regular JSON-LD arrays unless specific markup is provided (see ).
string
A string is a sequence of zero or more Unicode (UTF-8) characters, wrapped in double quotes, using backslash escapes (if necessary). A character is represented as a single character string.
number
A number is similar to that used in most programming languages, except that the octal and hexadecimal formats are not used and that leading zeros are not allowed.
true and false
Values that are used to express one of two possible boolean states.
null
The use null value. A key-value pair in the @context where the value, or the @id of the value, is null value within explicitly decouples a term's association with an IRI . A key-value pair in the body of a JSON-LD document whose value is used to ignore null has the same meaning as if the key-value pair was not defined. If @value , @list , or reset values. @set is set to null in expanded form, then the entire JSON object is ignored.

Furthermore, the following terminology is used throughout this document:

keyword
A JSON key that is specific to JSON-LD, specified in the JSON-LD Syntax specification [ JSON-LD ] in the section titled Syntax Tokens and Keywords .
context
A a set of rules for interpreting a JSON-LD document as specified in The Context of the [ JSON-LD ] specification.
IRI An Internationalized Resource Identifier as described in [ RFC3987 ]. Linked Data A set of documents, each containing a representation of a linked data graph . linked data graph JSON-LD document
An unordered labeled directed graph, where nodes are IRIs or Blank Nodes , or other values. A linked data graph JSON-LD document is a generalized representation serialization of a RDF graph collection of JSON-LD graphs as defined in [ RDF-CONCEPTS and comprises exactly one default graph ]. and zero or more named graphs .
named graph
A linked data named graph that is identified by a pair consisting of an IRI . or blank node (the graph name The IRI identifying ) and a named JSON-LD graph .
default graph
When executing an algorithm, the graph where data should be placed if a named graph is not specified. node A piece of information that is represented in a linked data The default graph . node definition A JSON object used to represent a node and one or more properties of that node. A JSON object is a node definition if it does not contain the keys @value , @list or @set and it has one or more keys other than @id . node reference A JSON object used to reference a node having only the @id key. blank node A node in the linked data graph that does not contain a de-referenceable identifier because it is either ephemeral in nature or does not contain information that needs to be linked to from outside of the linked data graph. A blank node is assigned an identifier starting with the prefix _: . property The IRI label of an edge in a linked data JSON-LD document which has no graph name .
subject A node in a linked data JSON-LD graph with at least one outgoing edge, related to an object node through a property . object
A node in labeled directed graph, i.e., a linked data graph with at least one incoming edge. quad A piece set of information that contains four items; a subject , a property , an object , and a graph name . literal An object expressed as a value such as a string, number or in expanded form. 3.2 JsonLdProcessor The JSON-LD processor interface is the high-level programming structure that developers use to access the JSON-LD transformation methods. Note The JSON-LD API signatures are the same across all programming languages. Due to the fact that asynchronous programming is uncommon in certain languages, developers may implement a processor with a synchronous interface instead. In that case, the callback parameter must not be included and the result must be returned as a return value instead. ] interface { }; 3.2.1 Methods compact Compacts nodes the given input using the context according to the steps in the Compaction Algorithm . The input must be copied, compacted and returned if there are no errors. If the compaction fails, an appropriate error must be returned via the callback. INVALID_SYNTAX A general syntax error was detected in the @context . For example, if a @type key maps to anything other than @id or an absolute IRI connected by edges , this error would be returned via the callback . LOAD_ERROR There was a problem encountered loading a remote context. LOSSY_COMPACTION The compaction would lead to a loss of information, such as a @language value. CONFLICTING_DATATYPES The target datatype specified in the coercion rule and the datatype for the typed literal do not match. LIST_OF_LISTS_DETECTED A list of lists was detected. The list of lists feature is not supported in this version of JSON-LD due to the algorithmic complexity associated with conversion to RDF. Parameter Type Nullable Optional Description input object or object[] or IRI Data Model ✘ ✘ The JSON-LD object or array section of JSON-LD objects to perform the compaction upon or an IRI referencing the JSON-LD document to compact. context object or IRI ✘ ✘ The context to use when compacting the input ; either in the form of an JSON object or as IRI . callback JsonLdCallback ✘ ✘ A callback that is called when processing is complete on the given input . options JsonLdOptions ✔ ✔ A set of options that may affect the expansion algorithm such as, e.g., the input document's base IRI . This also includes optimize , which if set will cause processor-specific optimization. Return type: syntax specification [ void JSON-LD ].
expand edge
Expands Every edge the given input according to the steps in the Expansion Algorithm . The input must be copied, expanded and returned if there are no errors. If the expansion fails, an appropriate error must be returned via the callback. INVALID_SYNTAX A general syntax error was detected in the @context . For example, if a @type key maps to anything other than @id or an absolute IRI , this error type will be set in the error sent to the callback . LOAD_ERROR There was a problem encountered loading has a remote context. LIST_OF_LISTS_DETECTED A list of lists was detected. The list of lists feature is not supported in this version of JSON-LD due to the algorithmic complexity direction associated with conversion to RDF. Parameter Type Nullable Optional Description input object or object[] or IRI ✘ ✘ The JSON-LD object or array of JSON-LD objects to perform the expansion upon or it and is labeled with an IRI referencing the JSON-LD document to expand. context object or IRI ✔ ✘ An optional external context to use additionally to the context embedded in input when expanding a blank node identifier . Within the input . callback JsonLdCallback ✘ ✘ A callback that is JSON-LD syntax these edge labels are called when processing is complete on the given input . options JsonLdOptions properties . Whenever possible, an edge ✔ ✔ A set of options that may should affect the expansion algorithm such as, e.g., the input document's base be labeled with an IRI . Return type: void
fromRDF node
Creates a JSON-LD document given an set of Quads . Parameter Type Nullable Optional Description input Quad [] ✘ ✘ A set of linked data graph s represented as an array of Quads . callback JsonLdCallback Every node ✘ ✘ A callback that is called when processing is complete on the given input . options JsonLdOptions ✔ ✔ A set of options that will affect the algorithm. This includes notType , which if set to true causes the resulting document to use rdf:type as a property, instead of @type . Return type: void toRDF Processes the input according to the Convert to RDF Algorithm , calling the provided callback for each Quad generated. INVALID_SYNTAX A general syntax error was detected in the @context . For example, if a @type key maps to anything other than @id or an absolute IRI , this error will be returned. LOAD_ERROR There was a problem encountered loading blank node , a remote context. LIST_OF_LISTS_DETECTED A list of lists was detected. This is not supported in this version of JSON-LD. Parameter Type Nullable Optional Description input object or object[] or IRI ✘ ✘ The JSON-LD object or array of JSON-LD objects to convert to RDF value , or a IRI referencing the JSON-LD document to convert to RDF. callback QuadCallback ✘ ✘ A callback that is called when a Quad is created from processing the given input . options JsonLdOptions ✔ ✔ list .
A set of options that may affect the conversion to RDF such as, e.g., the input document's base IRI . Return type: void 3.3 Callbacks Issue 153 Developers should note that the details of error handling and conformance handling are being actively debated. JSON-LD processors utilize a variety of callbacks in order to return information in an asynchronous manner to calling applications. This section details the parameters sent to those callbacks as well as the desired operation of the callbacks. 3.3.1 JsonLdProcessingError The JsonLdError type is used to encapsulate a variety of parameters that outline the cause of a particular JsonLdProcessor error. { }; Dictionary JsonLdProcessingError Members operation of type string a string representing the operation that was being performed when the conformance issue was raised. Valid values for the string include compact , expand , toRDF , and fromRDF . source of type array of object or object
An object reference to the original JSON-LD document being processed. sourceKey of type string The key value associated with the value that triggered the conformance issue. sourceValue of type object or object[] or string or number The value that triggered the conformance issue. type of type string a string representing the particular error type, such as LIST_OF_LISTS_DETECTED , as described in the various algorithms in this document. 3.3.2 JsonLdCallback The JsonLdCallback is used to return a processed JSON-LD representation as the result of processing an API method. ] interface { }; Methods processingComplete This callback is invoked when processing is complete. Parameter Type Nullable Optional Description error JsonLdProcessingError ✘ ✘ If the value is null , then no error occurred. If the value is non- null , a processing error occurred and the details will be contained within the error object. document object or object [] ✘ ✘ The processed JSON-LD document. Return type: void 3.3.3 QuadCallback The QuadCallback is called whenever the processor generates a quad during processing. ] interface { }; Methods quad This callback is invoked whenever a quad is generated by the processor. Parameter Type Nullable Optional Description error JsonLdProcessingError ✘ ✘ If the value is null , then no error occurred. If the value is non- null , a processing error occurred and the details will be contained within the error object. quad Quad ✘ ✘ If there is no error, the quad that was generated. Return type: void 3.3.4 ConformanceCallback The ConformanceCallback may be specified in the JsonLdOptions IRI via the conformanceCallback parameter. If specified, the callback is called whenever a recoverable conformance issue is detected. The developer may then determine whether or not processing should continue based on the type of conformance issue. ] interface { }; Methods issue This callback (Internationalized Resource Identifier) is invoked when a conformance issue is detected by the JSON-LD processor. Parameter Type Nullable Optional Description issue JsonLdProcessingError ✘ ✘ Details about the conformance issue. callback function ✘ ✘ A function that must be called when the program has determined how to respond to the conformance issue. A single parameter must be passed to the callback. The value of the parameter should be null if processing should continue by acting as if the key-value string that triggered the issue never existed. The issue should be passed conforms to the callback without modification if processing should stop. Return type: syntax defined in [ void RFC3987 ].
3.4 Data Structures This section describes datatype definitions used within the JSON-LD API. 3.4.1 absolute IRI The IRI datatype is a string representation of an
An absolute IRI . typedef DOMString IRI ; This datatype indicates that the string is interpreted as an Internationalized Resource Identifier defined in [ RFC3987 ] identifying a document, which when parsed as JSON yields either a JSON object or array . 3.4.2 JsonLdOptions The JsonLdOptions type is used to pass various options to the JsonLdProcessor methods. { }; Dictionary JsonLdOptions Members base of type IRI , nullable The Base IRI to use when expanding the document. This overrides the value of input if it is containing a IRI . If not specified and input scheme is not an IRI , the base IRI defaults to the current document IRI if in a browser context, or the empty string if there is no document context. compactArrays of type boolean , defaulting to true If set to true , the JSON-LD processor replaces arrays with just one element with that element during compaction. If set to false , all arrays will remain arrays even if they have just one element. conformanceCallback of type function , defaulting to null The purpose of this option is to instruct the processor about whether or not it should continue processing. If the value is null , the processor should ignore any key-value pair associated along with any recoverable conformance issue and continue processing. More details about this feature can be found in the ConformanceCallback section. flatten of type boolean , defaulting to false If set to a value that is not false , the JSON-LD processor must modify the output of the Compaction Algorithm or the Expansion Algorithm by coalescing all properties associated with each subject via the Flattening Algorithm . The value of flatten must path be either an IRI value representing the name of the graph to flatten, or true . If the value is true , then the first graph encountered in the input document is selected and flattened. optimize of type boolean , defaulting to false If set to true , the JSON-LD processor is allowed to optimize the output of the Compaction Algorithm to produce even compacter representations. The algorithm for compaction optimization is beyond the scope of this specification and thus not defined. Consequently, different implementations may optional query implement different optimization algorithms. useNativeTypes of type boolean , defaulting to true If set to true , the JSON-LD processor will try to convert datatyped literals to JSON native types instead of using the expanded object form when converting from RDF . xsd:boolean values will be converted to true or false . xsd:integer and xsd:double values will be converted to JSON numbers . fragment segments.
useRdfType of type boolean , defaulting to false If set to true , the JSON-LD processor will use the expanded rdf:type relative IRI as the property instead of @type when converting from RDF . The following data structures are used for representing data about RDF quads. They are used for normalization, and RDF conversion . 3.4.3 Quad The Quad interface represents an RDF Quad. See [ RDF-CONCEPTS ] definition for RDF triple , which most closely aligns to Quad . ] interface { }; Attributes graph of type Node , readonly, nullable If present, the name associated with the Quad identifying it as a member of a named graph . If it is missing, the quad is a member of the default graph . Issue 125 This element is at risk, and may be removed. object of type Node , readonly The object associated with the Quad . property of type Node , readonly The property associated with the Quad . Within JSON-LD, an RDF predicate is refered to as a property subject of type Node , readonly
The subject associated with the Quad . 3.4.4 Node Node is the base class of A relative IRI , BlankNode , and Literal . It is the IDL representation of a linked data graph node . ] interface { }; 3.4.5 an IRI A node that is an relative some other absolute IRI . ] interface { }; Attributes value of type DOMString , readonly The IRI identifier ; in the case of JSON-LD this is the node as a [ UNICODE ] string. base location of the document.
blank node 3.4.6 Blank Node
A node in the linked data a JSON-LD graph that does not contain a de-reference-able de-referenceable identifier because it is either ephemeral in nature or does not contain information that needs to be linked to from outside of the linked data graph . A JSON-LD graph.
blank node is assigned an identifier starting with the prefix _: and an implementation dependent, auto-generated suffix that is unique to all information associated with the particular blank node. ] interface { }; Attributes identifier of type DOMString , readonly
The temporary identifier of the A blank node . The identifier must not be relied upon in any way between two separate processing runs of the same document or with is a different document. Note Developers and authors must not assume string that the value of can be used as an identifier for a blank node will remain the same between two processing runs. BlankNode values are only valid for the most recent processing run on within the scope of a JSON-LD document. Blank node identifiers begin with BlankNode values will often be generated differently by different processors. Note Implementers must ensure that _: .
BlankNode JSON-LD value
A JSON-LD value values are unique within the current environment, two BlankNodes is a string , a number , true are considered equal if, and only if, their values are strictly equal. or false , a typed value , or a language-tagged string .
typed value 3.4.7 Literal Literals represent values such as numbers, dates and strings in RDF data.
A Literal typed value is comprised consists of three attributes: a lexical form of the value an optional language tag value, which is a datatype specified by string, and a type, which is an IRI .
Literals representing plain text in language-tagged string
A language-tagged string consists of a natural language may have string and a non-empty language tag specified by a string token, as specified in defined by [ BCP47 ], normalized to lowercase (e.g., 'en' , 'fr' , 'en-gb' ). They also have a datatype attribute such as xsd:string . If unspecified, the datatype defaults ]. The language tag must be well-formed according to xsd:string . Literals representing values with a specific datatype, such as the integer 72, may have a datatype attribute specified in the form of a IRI (e.g., xsd:integer ). See[ RDF-CONCEPTS ] definition for literal . ] interface { }; Attributes datatype of type IRI section 2.2.9 , readonly, nullable An optional datatype identified by a IRI . language of type DOMString , readonly, nullable An optional language tag as defined in [ BCP47 ], and must be normalized to lowercase.
value of type DOMString list , readonly
The lexical form A list is an ordered sequence of the Literal's value. IRIs , blank nodes , and JSON-LD values .

4. 5. Algorithms

All algorithms described in this section are intended to operate on language-native data structures. That is, the serialization to a text-based JSON document isn't required as input or output to any of these algorithms and language-native data structures must be used where applicable.

4.1 5.1 Algorithm Terms

active graph
The name of the currently active graph that the processor should use when processing.
active subject
the The currently active subject that the processor should use when processing.
active property
the The currently active property that the processor should use when processing. The active property is represented in the original lexical form, which is used for finding coercion type mappings in the active context .
active object
the The currently active object that the processor should use when processing.
active context
a A context that is used to resolve term s while the processing algorithm is running. The active context is the context contained within the processor state .
compact IRI a compact IRI is has the form of prefix and suffix and is used as a way of expressing an IRI without needing to define separate term definitions for each IRI contained within a common vocabulary identified by prefix . local context
a A context that is specified within a JSON object , specified via the @context keyword .
processor state
the The processor state , which includes the active context , active subject , and active property . The processor state is managed as a stack with elements from the previous processor state copied into a new processor state when entering a new JSON object .
JSON-LD input
The JSON-LD data structure that is provided as input to the algorithm.
JSON-LD output
The JSON-LD data structure that is produced as output by the algorithm.
term
A term is a short word defined in a context that may be expanded to an IRI
prefix compact IRI
A prefix is a term that expands to a vocabulary base compact IRI . It is typically used along with a has the form of prefix : suffix to form and is used as a compact way of expressing an IRI without needing to create an define separate term definitions for each IRI contained within a vocabulary. common vocabulary identified by prefix .
language-tagged string node object
A language-tagged string node object is represents zero or more properties of a literal node without a datatype, including in the JSON-LD graph serialized by the JSON-LD document. A JSON object is a language. See languaged-tagged string node object in [ RDF-CONCEPTS if it exists outside of the JSON-LD context ]. and:
  • it does not contain the @value , @list , or @set keywords, or
  • it is not the top-level JSON object in the JSON-LD document containing the @graph keyword.
typed literal list object
A typed literal list object is a literal JSON object with an associated that has a @list member.
IRI scalar which indicates the literal's datatype. See
A scalar is either a JSON string , number , true , or false .
literal quad in
An RDF triple as specified by [ RDF-CONCEPTS ]. ] augmented with a a fourth component, a graph name .

4.2 5.2 Context Processing Expansion Algorithm

Processing of JSON-LD data structure is managed recursively. During processing, each rule is applied using information provided by the The algorithm takes three input variables: an active context . Processing begins by pushing a new processor state onto , an active property , and an element to be expanded. To begin, the processor state stack. If a local active context is encountered, information from set to the local context result of performing, Context Processing is merged into on the active context . The active context passed expandContext , or empty if expandContext is used for expanding properties and values of a JSON object null , active property (or elements of an array) using a term mapping . It is also used to maintain coercion mapping s from terms to datatypes, language mapping s from terms set to language codes, and list mapping s null , and set mapping s for terms. Processors must element use is set to the lexical form of JSON-LD input . This algorithm expects the property when creating JSON-LD input to be a mapping, well-formed JSON-LD document as lookup is performed on lexical forms, not expanded IRI representations. A local context defined in [ JSON-LD ].

  1. If element is identified within a JSON object scalar , expand it according to the Value Expansion having a @context algorithm, passing copies of the active context and active property with a string and return.
  2. If element is null , return.
  3. If element is an array or a JSON object value. When processing a local context , special processing rules apply:
    1. Create a new, initialize an empty local context . array result .
    2. Let Expand each context item be the value by recursively using this algorithm, passing copies of @context If context equals null , clear the active context and active property .
    3. If the active property's container mapping is set to @list and the expanded context item is an array , process each element as or a list object trigger a LIST_OF_LISTS_DETECTED error.
    4. If the expanded context item in order by starting at Step 2.1 . is null , drop it.
    5. If Otherwise, if the expanded context item is a string an array , it must merge its entries with result's have a lexical form of IRI . entries.
    6. Expand Otherwise, append context item according to IRI Expansion . Dereference context result .
    7. If the resulting document is a JSON document, extract the top-level @context element using the JSON Pointer "/@context" as described in [ JSON-POINTER ]. Set Finally, set context element to the extracted content result and process it by starting at Step 2.1 . return.
  4. If Otherwise, context element is a JSON object , perform the following steps: must be an object.
    1. If context element has a @language @context property, it must have a value of a simple string member, update the active context with according to the lexical form described steps outlined in [ BCP47 Context Processing ], or null . Add the language to and remove the local context . @context member.
    2. If Initialize an empty JSON object value has a @vocab key, it must result have a value of a simple string with the lexical form of an absolute IRI , or null . Add the vocabulary mapping to the local context . and
    3. Otherwise, for
    4. then process each property and value in context element perform the following steps: ordered by property as follows:
      1. If the property's value is active context contains a simple string property generator for property set expanded property to its IRIs , determine otherwise set it to the IRI mapping value by performing result of expanding property according to the steps outlined in IRI Expansion on (passing true for the associated value. vocabRelative flag).
      2. If the result of the IRI mapping is an absolute IRI , merge the property into the local context term mapping , unless the expanded property is a JSON-LD keyword null , in which case return an error. Otherwise, if skip the property's current property - value is null remove mapping, coercion, container pair and language information associated with property from the local context . Otherwise, continue to the next property 's - value must be a JSON object . pair in element .
      3. If the expanded property is a JSON-LD keyword and the value has , process it as follows:
        1. If expanded property equals @id , set the @language or @type @id properties, return an error. Issue member of result to the result of expanding value according the Undecided if @type or IRI Expansion algorithm (passing @graph true can take for the documentRelative flag). If value is not a @container string trigger an INVALID_ID_VALUE with @set . error.
        2. If the expanded property has equals @type , set the form of term , its value must have an @id @type property with a string value which must member of result have to the form result of a term , compact IRI , or absolute IRI . Determine expanding value according the IRI mapping by performing IRI Expansion algorithm on the associated value. If (passing true for both the result of documentRelative and the IRI mapping vocabRelative flag). If value is neither a string nor an absolute IRI , merge the array of strings trigger an INVALID_TYPE_VALUE error. Empty arrays are ignored.
        3. If expanded property into equals @value , set the local context @value member of result to value . If value is neither a scalar term mapping . nor null trigger an INVALID_VALUE_OBJECT_VALUE error.
        4. If the expanded property has equals @language , set the form of @language member of a compact IRI or absolute IRI , result to the lowercased value . If value may have is not a @id string , trigger an INVALID_LANGUAGE_VALUE error.
        5. If expanded property with a string value which must have equals @annotation , set the form @annotation member of result to value . If value is not a term , compact IRI , or absolute IRI . Determine the IRI mapping by performing IRI Expansion string on the associated value. trigger an INVALID_ANNOTATION_VALUE error.
        6. If expanded property equals @set or @list , set the result expanded property member of result to the IRI mapping is an absolute IRI , merge the result of expanding property value into by recursively using this algorithm, passing copies of the local active context term mapping and active property .
        7. If the value expanded property has a equals @type @graph , set the @graph property, its value must member of result have to the form result of expanding value by recursively using this algorithm, passing copies of a term , compact IRI , absolute IRI , or the keyword active context and @id . Determine the IRI by performing IRI Expansion on @graph as active property .
        8. Continue with the associated value. next property - value pair from element .
      4. If the result of the IRI mapping expanded property is not an absolute IRI or @id , merge into the local context coercion mapping using the lexical value of ,i.e., it doesn't contain a colon, continue with the next member from property element .
      5. If the Otherwise, if value has a @container property, its value must property's be @list or @set . Merge the list container mapping or is set mapping into the local context to @language
        1. Initialize a new empty array using the lexical value of the property language map values .
        2. If the Process each key - val pair of value has ordered by key as follows:
          1. If val is not an array, transform it to one.
          2. For each item of val , construct a new JSON object consisting of two members: @language property but no @type @value property, the value of set to the currently processed item and @language property must set to the lowercased key . If val be is not a string or null . Merge , trigger a LANGUAGE_MAP_INVALID_VALUE error. Otherwise append the object to language mapping into the local context using the lexical map values .
        3. Set value of the to property language map values .
      6. Merge the local context Otherwise, if property's container mapping into is set to @annotation
        1. Initialize a new empty array annotation map values .
        2. Process each key - val pair of value ordered by key as follows:
          1. If val is not an array, transform it to one.
          2. Expand val by recursively using this algorithm, passing copies of the active context and active property .
          3. Repeat Step 2.4.2 until no entries are added Add to each item of val a member @annotation set to key if no such member exists yet and append the local context . resulting JSON object to annotation map values .
        3. Set value to annotation map values .
      7. Note It can be difficult to distinguish between a compact IRI
      8. Otherwise, expand value by recursively using this algorithm, passing copies of the active context and an absolute IRI , property as a compact IRI may seem to be a valid IRI active property .
      9. If the expanded scheme value equals null , continue with the next property - value pair from element . When performing repeated IRI expansion, a term used as a prefix may not have a valid
      10. If property's container mapping due to dependencies in resolving term definitions. By continuing Step 2.3.2 until no changes are made, mappings to IRIs created using an undefined term prefix will eventually expand is set to an absolute IRI s. 4.3 IRI Expansion Keys @list and some values are evaluated to produce an IRI . This section defines an algorithm for transforming a value representing an IRI into is either not an actual IRI . IRIs JSON object may be represented as an absolute IRI , a term , a compact IRI , or as a value relative to @vocab . An absolute IRI is defined in [ RFC3987 JSON object ] containing a without an @list member, replace scheme value along with a JSON object with an @list member whose value is set to path and optional query value and fragment segments. A relative IRI is (wrapped in an IRI that is relative some other absolute IRI array ; in the case of JSON-LD this if it is not already one).
      11. If expanded property is the base location of the document. The algorithm for generating an IRI is: array ,
        1. If the active context contains a term label all blank nodes mapping for the in value with blank node identifiers by using a case-sensitive comparison, use the mapped Label Blank Nodes Algorithm .
        2. Then, for each iri of expanded property merge a copy of value as an IRI . into the iri member of the result JSON object .
      12. Otherwise, split the merge value into a the prefix iri member of the result JSON object .
    5. Set element to result and suffix numProperties from to the first occurrence number of ':'. members of result .
    6. If the prefix is a '_' (underscore), the value represents a named blank node . element has an @annotation member, decrease numProperties by 1.
    7. If the active context contains a term mapping for prefix element using a case-sensitive comparison, and has an @value member,
      1. decrease suffix numProperties does not does not begin with '//' (i.e., it does not match a by 1.
      2. If hier-part element including has an @language member, decrease authority numProperties (as defined in [ RFC3986 ]), generate an IRI by prepending the mapped prefix to the (possibly empty) suffix using textual concatenation. Note that an empty suffix 1 and no suffix (meaning check that the value contains no ':' string at all) are treated equivalently. of the @value member is a string. If not, trigger an INVALID_LANGUAGE_TAGGED_STRING error.
      3. Otherwise, if the IRI being processed does not contain a colon element has an @type member, decrease numProperties by 1 and is a property, i.e., a key in a JSON object , or check that the value of the @type and the active context has member is a @vocab string. If not, trigger an INVALID_TYPED_VALUE mapping, join error.
      4. If numProperties is greater than 0, trigger an INVALID_VALUE_OBJECT error.
      5. If the mapped value to of the suffix using textual concatenation. @value member equals null , set element to null .
      6. Otherwise, if the IRI being processed does not contain a colon and Return.
    8. If element has an @type member whose value is not a property, i.e., not a key in a JSON object treat an array , transform it as a relative IRI to an array .
    9. If element has an @list or @set member and resolve it against the base IRI as per [ RFC3986 ] using only the basic algorithm in section 5.2. Neither Syntax-Based Normalization numProperties nor is greater than 1, trigger an INVALID_SET_OR_LIST_OBJECT error.
    10. Otherwise, if Scheme-Based Normalization element (described in sections 6.2.2 and 6.2.3 of [ RFC3986 ]) are performed. Characters additionally allowed in IRI references are treated in has an @set member, set element to the same way that unreserved characters are treated in URI references, per section 6.5 value of [ RFC3987 ]. that member.
    11. Otherwise, use the value directly as if element has just an IRI . @language member, set element to null.

If, after the algorithm outlined above is run, the resulting element is an JSON object with just a @graph member, element is set to the value of @graph 's value. Finally, if element is a JSON object , it is wrapped into an array .

4.4 5.3 IRI Compaction Context Processing

Some keys Processing of JSON-LD data structure is managed recursively. During processing, each rule is applied using information provided by the active context .

The active context contains the active term definitions which specify how properties and values are expressed using IRI have to be interpreted as well as the current vocabulary mapping and the default language . Each term definition s. This section defines an algorithm for transforming consists of an IRI ( iri ) to mapping and optionally a term type mapping from terms to datatypes or compact language mapping from terms to language codes, and a container mapping . If an IRI mapping maps a term to multiple IRIs it is said to be a property generator .

If a local context using is encountered, information from the term local context s specified in is merged into the active context . A local context using is identified within a JSON object having a @context member with a string , array or a JSON object value.

This algorithm specifies how the active context is updated with a local context . The algorithm takes three input variables: an optional active context , a local context , and an array of already included remote contexts value remoteContexts . To begin, remoteContexts is initialized to an empty array.

4.4.1

All calls of the IRI Compaction Algorithm The Expansion algorithm for generating a compact IRI is: pass the value specified in the algorithm along with the active context , the currently being processed local context , and true for the vocabRelative flag.

  1. Create If the local context is not an empty list of terms array, transform it to one.
  2. Process each item terms context that will be populated with term of the local context s that are ranked according to how closely they match value . Initialize as follows:
    1. If highest rank context to 0 , equals null , reset the active context and set continue with the next item.
    2. If context is a flag string :
      1. Expand list container context according to false . IRI Expansion .
      2. For each If term context is in the active remoteContexts array, raise an RECURSIVE_CONTEXT_INCLUSION error. Otherwise, add context : to remoteContexts .
      3. Dereference context .
      4. If the resulting document is a JSON document consisting of a top-level JSON object that has a @context member recursively invoke this algorithm passing a copy of active context , the value of the @context member as local context , and a copy of the term remoteContexts 's array. Relative IRIs are expanded using the remote context's IRI is not a complete match against iri , continue to . Otherwise raise an INVALID_REMOTE_CONTEXT error.
      5. Continue with the next item from term context .
    3. If value context is not a JSON object containing only , raise an INVALID_LOCAL_CONTEXT error.
    4. Otherwise, if context is an JSON object , perform the property @list : following steps:
      1. If term context has a @container @vocab member: if its value is neither an absolute IRI , i.e., it does not contain a colon ( : ), nor null , trigger an INVALID_VOCAB_MAPPING error; otherwise set the active context's vocabulary mapping to @set , continue to its value and remove the next @vocab member from term context .
      2. If list container context is has a true @language and term does not have member: if its value is neither a container string nor null , trigger an INVALID_DEFAULT_LANGUAGE error; otherwise set the active context's default language to its value and remove the @list @language and member from context .
      3. For each other key - value is null , continue to pair in context perform the following steps:
        1. Remove the next term key - value pair from context .
        2. Otherwise, if If term key has is a container set to @list , JSON-LD keyword , continue to with the next term . key - value pair.
        3. Set If rank value to equals null , replace the term rank definition of for value key by passing passing term , value , and in the active context with an IRI mapping set to null and continue with the Term Rank Algorithm . next key - value pair.
        4. If rank value is greater than 0 : If a string , expand it according to the IRI Expansion algorithm and replace the term definition for key has a container in the active context with an IRI mapping set to @set , then add 1 to the expanded rank value . Continue with the next key - value pair.
        5. If value is not a JSON object containing only the property @list , trigger an INVALID_TERM_DEFINITION and error
        6. If term definition for list container key is false and exists in the active context , remove it.
        7. Initialize a new, empty term definition definition .
        8. If value has a an container @id set to @list , then set list container to true , clear member with a value terms , set val :
          1. if highest rank val to rank , and add is null , set term definition to terms val .
          2. Otherwise, if rank val is greater than or equal to an array , process each highest rank : item in the array:
            1. If if rank item is greater than a string expand it according the IRI Expansion algorithm .
            2. otherwise, raise an INVALID_PROPERTY_GENERATOR error.
          3. if highest rank , clear val is an array , lexicographically sort terms val and set highest rank definition to rank val .
          4. Add Otherwise, if term val is a string , expand it according the IRI Expansion algorithm and set definition to terms val .
        9. If the IRI mapping of terms definition is empty, and the active context set to null has a @vocab which is or a prefix of keyword , store the iri definition where as the resulting relative IRI is not a term definition for key in the active context . The resulting relative IRI is and continue with the unmatched part of next iri key - value pair from context .
        10. If terms is empty, add a compact Otherwise, set the IRI mapping representation of iri definition for each term in the active context which maps to an the result of expanding key according the IRI which is Expansion algorithm .
        11. If value has an @type member with a prefix for value iri val and val where the resulting compact IRI is not a term string in the active context . The resulting compact or does not expand to an absolute IRI is the term associated with using the partially matched IRI in Expansion algorithm , raise an INVALID_TYPE_MAPPING error. Otherwise set the active context IRI mapping concatenated with a colon (:) character and the unmatched part of iri definition to the expanded val .
        12. If Otherwise, if terms is empty, the IRI being processed is a property or the value of @type and has an @vocab @language member with a value val that is not a string or null and matches , set the beginning language mapping of iri , return definition to the unmatched portion of lowercased iri val . Otherwise return If iri . val is neither a string nor null , raise an INVALID_LANGUAGE_MAPPING error.
        13. Otherwise, return the shortest and lexicographically least f value has an @container member with a value in terms val that equals @list , @set , or @annotation , set the container mapping of definition to val . If val is not one of those values, raise an INVALID_CONTAINER_MAPPING error.

4.4.2 5.4 Term Rank Algorithm IRI Expansion

When selecting among multiple possible terms for a given property, it may be that multiple terms In JSON-LD documents keys and some values are defined with the same evaluated to produce an IRI , but differ in @type , @container or @language . The purpose . This section defines an algorithm for transforming strings representing an IRI into an absolute IRI . If IRI expansion occurs during context processing, the local context that is being processed is passed to this algorithm. After application of this algorithm, values processed by this algorithm is are said to take a term be in expanded IRI form , although this may also include blank node identifiers and a value and give it a term rank . The selection can then be based, partly, on the term having the highest term rank JSON-LD keywords .

Given The algorithm takes two mandatory and four optional input variables: a term term , value , and to be expanded, an active context , two flags documentRelative and vocabRelative specifying whether value should be interpreted as relative IRI determine against the term rank document's base IRI or the active context's using vocabulary mapping , along with an local context passed when this algorithm is used in Context Processing , and finally an array path which is used to detect cyclic IRI mappings . If not passed, the following steps: two flags are set to false and path is initialized to an empty array by default.

The algorithm for generating an IRI is:

  1. If value is null , term rank is 3 . Otherwise, if or a JSON-LD keyword , return value is as is.
  2. If a JSON object local context containing only the property @list : has been passed
    1. If the @list property and value is an empty array, if in the term path has @container array, raise a CYCLIC_IRI_MAPPING set error. Otherwise append value to @list , term rank is 1 , otherwise 0 . path .
    2. Otherwise, If local context contains an IRI mapping for value that is not a property generator return the sum result of recursively calling this algorithm passing the term rank IRI s of the IRI mapping as new value , the active context and local context , path , and true for every entry in the list. vocabRelative flag. If the result is a property generator , raise an PROPERTY_GENERATOR_IN_TERM_DEFINITION error.
  3. Otherwise, If an IRI mapping exists for value must be a node definition , node reference , or a JSON object in the active context having that is not a @value . property generator return the value of the IRI mapping .
  4. If value has contains a @value colon ( : property: ), perform the following steps:
    1. If Split value has a @type property matching into a @type coercion for term , term rank is 3 , otherwise if prefix and term suffix has no @type at the first occurrence of a colon ( : coercion and no @language , term rank is 1 , otherwise 0 . ).
    2. Otherwise, if @value is not a string , if If term suffix has no begins with @type // or prefix equals @language it is 2 _ , otherwise 1 . Otherwise, if return value as is.
    3. If a local context has no @language property, if been passed, expand term prefix has @language null , or by recursively invoking this algorithm passing term prefix has no @type or @language and as value , the active context has no and local context , path , and @language , term rank true for the vocabRelative flag. If the expanded prefix contains a colon ( : ) generate and return an IRI is 3 , otherwise 0 . by prepending the expanded prefix to the (possibly empty) suffix using textual concatenation.
    4. Otherwise, if the active context contains an IRI mapping for value prefix has that is not a @language property matching a @language definition for generator , generate and return an IRI by prepending the IRI mapped to term prefix (or to the (possibly empty) term suffix has no @type or using textual concatenation.
  5. Otherwise, if the vocabRelative flag is set to @language true definition and @language in the active context matches contains a vocabulary mapping , generate and return an IRI by prepending the value @language ), term rank IRI is 3 , otherwise if of the vocabulary mapping to the term value has no @type coercion and no @language , term rank is 1 , otherwise 0 . using textual concatenation.
  6. Otherwise, if the term documentRelative has @type coerced flag is set to @id true , term rank resolve value against the base IRI as per [ RFC3986 ] and return the resulting IRI . Only the basic algorithm in section 5.2 of [ RFC3986 ] is 3 , otherwise if used; neither term Syntax-Based Normalization has no @type coercion nor Scheme-Based Normalization (as described in sections 6.2.2 and no @language , term rank 6.2.3 of [ RFC3986 is 1 , otherwise 0 . ]) are performed. Characters additionally allowed in IRI references are treated in the same way that unreserved characters are treated in URI references, per section 6.5 of [ RFC3987 ]
  7. Return term rank . Otherwise return value as is.

If the result of the algorithm above is a blank node identifier , i.e., a string that begins with _: , and no local context has been passed, generated a new blank node identifier before returning the final result.

4.5 5.5 Value Expansion

Some values in JSON-LD can be expressed in a compact form. compacted form . These values are required to be expanded at times when processing JSON-LD documents. A value is said to be in expanded form after the application of this algorithm.

The algorithm for expanding a value takes an active property and active context . It is implemented as follows:

  1. If value is null , the return null .
  2. Initialize an empty object value is already expanded. result .
  3. If active property is @graph or the target of an active property's type mapping is set to @id coercion, expand the value into an object with , add a key-value pair to result where the key is @id and the value is the expanded IRI result of expanding value according to the IRI Expansion algorithm rules. Otherwise, if active property is not a keyword , then expand passing true for the value documentRelative into an object: flag. Then return result .
  4. Set the first Add a key-value pair to result where the key is @value and the unexpanded value is value .
  5. If the active property is the target of typed literal coercion, set the second has a type mapping , add a key-value pair to result where the key is @type and the associated coercion datatype expanded according to value is the IRI Expansion rules. associated with the type mapping or a newly generated blank node identifier if the type mapping is set to a blank node identifier .
  6. Otherwise, if value is a string and the active property is the target of has a language tagging, mapping or an default language is set in the second active context , add a key-value pair to result where the key is @language and the value of is the language tagging from tag associated with the language mapping or the active context property or the default language .
  7. Otherwise, Return value is already expanded. result .

4.6 5.6 Value Compaction Label Blank Nodes Algorithm

Some values, such as IRIs and typed literals , may be expressed in an expanded form ( expanded value ) in JSON-LD. These values are required to be compacted at times when processing JSON-LD documents. The algorithm for compacting takes a single input variable: an expanded value value element takes an active property and active context to be labeled with blank node identifiers . It is implemented as follows:

  1. If value element only has one property and the active context has no default language, then the compacted value is the value of @value . an array , recursively apply this algorithm to all its items.
  2. Otherwise, if active property is @graph , the compacted value element is the value associated a JSON object with the a @id @list key, processed according member, recursively apply this algorithm to all items of the IRI Compaction steps. @list member's value.
  3. Otherwise, if the active context contains element is a coercion target for the JSON object
    1. For each key that matches the expression of the value, compact the - value using the following steps: pair ordered by key recursively apply this algorithm to value .
    2. If the coercion target element is a node object without an @id , the compacted value is the value associated with the member, create a new @id key, processed member and assign it a new blank node identifier according to the IRI Compaction Generate Blank Node Identifier steps. algorithm.
    3. If the coercion target

5.7 Generate Blank Node Identifier

This algorithm is used to generate new blank node identifiers or to relabel existing blank node identifiers with a typed literal , new one to avoid collision by the compacted value introduction of new ones. It needs to keep an identifier map , a counter , and a prefix between its executions to be able to generate new blank node identifiers . The counter is the value associated with the initialized to @value 0 key. Otherwise, if and value prefix contains an is set to @id _:t key, the compacted value is by default.

The algorithm takes a single input variable value identifier with the value of @id processed according to the IRI Compaction steps. which might be null .

  1. Otherwise, if If the active context identifier is not null contains a @language , which matches the @language of the value, or the value has only a @value key, the compacted value and is in the value associated with identifier map , return the @value key. mapped identifier.
  2. Otherwise, if the value contains generate a @type key, the compacted value is new value blankNodeIdentifier with the by concatenating prefix and counter .
  3. Increment counter by @type value processed according to the IRI Compaction steps. 1 .
  4. Otherwise, the value If identifier is not modified. null , create a new entry in identifier map set to blankNodeIdentifer .
  5. Return blankNodeIdentifier .

4.7 Expansion Expansion is the process of taking a JSON-LD document and applying a context such that all IRI , datatypes, and literal values are expanded so that the context is no longer necessary. JSON-LD document expansion is typically used as a part of other JSON-LD API methods. For example, assume the following JSON-LD input document: { "@context": { "name": "http://xmlns.com/foaf/0.1/name", "homepage": { "@id": "http://xmlns.com/foaf/0.1/homepage", "@type", "@id" } }, "name": "Manu Sporny", "homepage": "http://manu.sporny.org/" } Running the JSON-LD Expansion algorithm against the JSON-LD input document provided above would result in the following output: { "http://xmlns.com/foaf/0.1/name": "Manu Sporny", "http://xmlns.com/foaf/0.1/homepage": { "@id": "http://manu.sporny.org/" } } 4.7.1 5.8 Expansion Compaction Algorithm

The algorithm takes three four input variables: an active context , an inverse context , an active property , and an element to be expanded. compacted. To begin, the active context is set to the result of performing, performing Context Processing on the passed context , or empty if inverse context is null set to the result of creating an inverse context from the active context , active property is set to null , and element is set to the result of performing the Expansion Algorithm on the JSON-LD input .

  1. If element is an array , process
    1. Initialize a new empty array result .
    2. Process each entry item in element recursively using this algorithm, passing copies a copy of the active context , inverse context , and the active property . Add each compacted item to result unless it is null .
    3. If result has a @container single item and the compactArrays option is set to @list and any entry in true , return that item; otherwise return result .
  2. If element is an array , or is not a JSON object containing a @list property, it is already in compact form, return an error, it as lists of lists are not allowed. If the expanded entry is null, drop it. is.
  3. If it's an array, merge its entries with element 's entries. Otherwise, if has an @value or @id member, replace element is an object with the result of the Value Compaction algorithm . If the updated element has is a @context property, update the active context according to the steps outlined in Context Processing scalar , return it as it cannot be further compacted.
  4. Initialize a new empty JSON object and remove the @context property. result.
  5. Then, proceed and process Process each property and value in element ordered by property as follows:
    1. Remove If property from element , expand is a JSON-LD keyword
      1. and property equals @id , compact value according to the steps outlined in rules of the IRI Expansion Compaction algorithm . Set the active property to the original un-expanded
      2. Otherwise, if property if equals @type , compact property value is not a keyword . If (or each item of property value does not expand to a keyword or if it is an absolute array ) according the rules of the IRI Compaction algorithm (i.e., it doesn't contain a colon), continue with the next property from element . vocabRelative flag set to true . If value is null an array and consisting of just one item, replace property value is not @value , continue with the next property from element . that item.
      3. If the Otherwise, if property is equals @id the @graph , compact value must be by recursively invoking this algorithm, passing a string . Expand copy of the active context , inverse context , and value property according as active property ensuring that the result is an array .
      4. Set active property to the result of performing IRI Expansion . Compaction on property .
      5. Otherwise, if Set the active property member of result to value .
      6. Continue with the next property is @type : - value pair from element .
    2. If value is a string an empty array , expand according
      1. set active property to the result of performing IRI Expansion . Otherwise, if Compaction on value property with the vocabRelative flag set to true .
      2. If active property is a JSON Object object , i.e., it must be empty (used for Framing is a property generator , set active property ). to the result of performing the Find and Remove Property Generator Duplicates algorithm passing element , property , null for value, the active context , and active property .
      3. Otherwise, if Ensure that value result is has an active property member; if not create it and set its value to an empty array , all elements must be string s. Expand .
      4. Continue with the next property - value pair from element .
    3. Otherwise perform the following steps for each item of its entries according value :
      1. Set active property to the result of performing IRI Expansion . Compaction on property with the vocabRelative flag set to true .
      2. Otherwise, if If active property is a JSON object , i.e., it is a property generator , set active property to the result of performing the Find and Remove Property Generator Duplicates algorithm passing element , property , item , the active context , and active property .
      3. If the active property's container mapping is set to @value @language or @language @annotation the
        1. Unless value must not result be a has already an active property member, create one and initialize its value to an empty JSON object or an array . This object is called mapObject .
        2. Otherwise, if the Set property index is to the value of the @list @language or @set @annotation expand member of item (depending on the value of the active property's container mapping ).
        3. First compact item recursively using the Value Compaction algorithm passing index as containerValue , then compact it by recursively invoking this algorithm, algorithm passing copies a copy of the active context , inverse context , and the active property . .
        4. If no index member exists in the expanded mapObject create one and set its value to item is not an array , convert ; otherwise append item to the index member (converting it to an array . If if it is not one already).
        5. Continue with the next property is @list and any entry in - value pair from element .
      4. If item is a JSON object containing an having a @list property, return an error, as lists member,
        1. compact the value of lists are not supported. that member by recursively invoking this algorithm passing a copy of the active context , inverse context , and the active property ensuring that the result is an array .
        2. Otherwise, expand If the active property's container mapping is set to @list , set the active property member of result to the value of item's @list member. If such an member already exists in result, raise an COMPACTION_TO_LIST_OF_LISTS error; otherwise continue with the next property - value pair from element .
      5. If item is a JSON object , compact it by recursively using invoking this algorithm, algorithm passing copies a copy of the active context , inverse context , and the active property .
      6. If no active property member exists in result is not a keyword create one and set its value to item ; otherwise append item to the active property has a member (converting it to an array if it is not one already).
      7. If the compactArrays option is set to @container false or the active property's container mapping is set to @list and or @set , convert the expanded value of the active property member of result to an array if it is not null , convert one already.

    If, after the algorithm outlined above is run, the resulting value element to is an array replace it with a new JSON object with an a single member whose name is the result of compacting the value @list @graph property with the IRI Compaction algorithm and whose value is set element . Finally, add a @context property to value element (unless and set it to the initially passed context .

5.9 IRI Compaction Algorithm

This section defines an algorithm for transforming an IRI to a term or compact IRI . If a value is already in that form). Convert passed it is used to choose the best matching term .

This algorithm takes three mandatory and two optional parameters. The mandatory parameters are the value iri to array form unless be compacted, an active context , and an inverse context . Optionally it is possible to pass a value is null and a vocabRelative flag which specifies whether the passed iri should be compacted using the active context's or vocabulary mapping . If the property vocabRelative flag is not set it defaults to @id , @type , @value , or @language false .

The algorithm for generating a compact IRI is:

  1. If Initialize a variable value result is not to null .
  2. If an entry for iri exists in the inverse context , either merge perform the following steps:
    1. If a value into has been passed, perform the following steps:
      1. Initialize queryPath , which will be used to query the inverse context , to an existing empty array
      2. Initialize property container property of to @set , element typeOrLanguage , and typeLanguageValue or create to null .
      3. If value is a new JSON object
        1. and it has an @annotation member, set property container property with to @annotation .
        2. If value as value. has an @id member, set typeOrLanguage to @type and typeLanguageValue to @id .
        3. If the processed Otherwise, if element value has an @value property member,
          1. and an @type member, set element must not typeOrLanguage have more than one other property, which can either be to @language @type or and typeLanguageValue to the value of the @type with a string value. member of value .
          2. Otherwise, if it has an @language member, set typeOrLanguage to @language and typeLanguageValue to the value of the @value @language equals null , replace member of element value . If value with has no @annotation member, set container to @language
          3. Otherwise, if the value of value's @value member is is a string , set typeOrLanguage to @language and typeLanguageValue to @null .
        4. Otherwise, if element value has an @type @list property member,
          1. If the @list member has at least one item, update container , typeOrLanguage , and its value is typeLanguageValue by recursively running the steps 2.1.2 to 2.1.3.4 (which will never be true since list of lists are not in allowed) of this algorithm passing the form first item of an array , convert it to an array . value's @list member as new value .
          2. If element value has an no @set @annotation or member, set container to @list property, it must .
          3. Starting from the second item of value's @list member, recursively run the steps 2.1.2 to 2.1.3.4 (which will never be true since list of lists are not allowed) of this algorithm passing the only property. Set item as new element value . If the resulting typeOrLanguage to or typeLanguageValue differ from the current value of @set ; leave typeOrLanguage or typeLanguageValue , set both to null and stop processing the @list untouched. items.
      4. If the element container has just a equals @language property, @list , set the first item of element queryPath to an array consisting of the two elements @list and null . ; otherwise set it to an array consisting of three elements where the first element is the value of container and the other two elements are @set and @null .
      5. If typeOrLanguage is null , set the second and the the third item of queryPath to an array consisting of a single element @null .
      6. Otherwise, expand set the second item of element queryPath according to the Value Expansion an array rules, passing copies consisting of two elements where the first element is the value of typeOrLanguage and the active context second element is @null . Set the third item of queryPath to an array whose first element typeLanguageValue and active property . whose second element is @null .
      7. If, after
      8. Query the algorithm outlined above is run, inverse context and store the resulting result in element result .
      9. If result is an a a string or a JSON object with just a @graph term property, member, return element result .
    2. Otherwise, if the entry for iri is set to in the value of inverse context has a @graph term 's member, return its value. Finally, if
  3. For each element termIri is - termDefinition pair in inverse context sorted in reverse order by termIri the (longest termIri comes first), perform the following steps:
    1. If termDefinition does not have a JSON object , term member, i.e., it is wrapped into an array a property generator, continue with the next termIri - termDefinition pair from inverse context . 4.8 Compaction Compaction
    2. Otherwise, if iri begins with termIri and is longer than termIri , generate a compact IRI by concatenating the process value of taking the term member of termDefinition with a JSON-LD document colon ( : ) character and applying a context such that the most compact form unmatched part of iri .
    3. If the document is generated. JSON is typically expressed in a very compact, key-value format. That is, full IRIs are rarely used as keys. At times, a JSON-LD document may be received that is not in its most compact form. JSON-LD, via the API, provides a way to resulting compact a JSON-LD document. For example, assume the following JSON-LD input document: { "http://xmlns.com/foaf/0.1/name": "Manu Sporny", "http://xmlns.com/foaf/0.1/homepage": { "@id": "http://manu.sporny.org/" } } Additionally, assume the following developer-supplied JSON-LD context: { "@context": { "name": "http://xmlns.com/foaf/0.1/name", "homepage": { "@id": "http://xmlns.com/foaf/0.1/homepage", "@type": "@id" } } } IRI Running has an entry in the JSON-LD Compaction algorithm given active context , continue with the next termIri - termDefinition pair from inverse context supplied above against as the JSON-LD input document provided above would compact IRI cannot be used.
    4. Otherwise, if result in is null , return the following output: { "@context": { "name": "http://xmlns.com/foaf/0.1/name", "homepage": { "@id": "http://xmlns.com/foaf/0.1/homepage", "@type": "@id" } }, "name": "Manu Sporny", "homepage": "http://manu.sporny.org/" } compact IRI The compaction algorithm also enables the developer to map any expanded format into an application-specific compacted format. While ; if it is not null, set the context provided above mapped http://xmlns.com/foaf/0.1/name term member of result to name , it could have also mapped it to any arbitrary string provided by the developer. compact IRI 4.8.1 Compaction Algorithm The algorithm takes three input variables: an active context , an active property , and an return element result .
  4. If the vocabRelative flag is set to be compacted. To begin, true , the active context is set to has a vocabulary mapping , and iri begins with the result IRI of performing Context Processing the vocabulary mapping on but is longer
    1. Set vocabIri to the passed unmatched part of context , iri .
    2. If there does not exist an entry for vocabIri in the active property context , return vocabIri if result is null ; if it is not null set the term member of result to vocabIri and return result .
  5. If result is null , and return element iri is as is.
  6. Otherwise set to the result term member of performing result to iri and return result .

5.10 Inverse Context Creation

An active context as produced by the Expansion Algorithm Context Processing on algorithm is very efficient for expanding terms and compact IRIs to IRIs but is of limited use for the JSON-LD input opposite operation: IRI compaction . This removes any existing Hence, this algorithm introduces the notion of an inverse context which brings the same efficiency to IRI compaction . An inverse context a tree of JSON objects which allow the given to efficiently select a term for a IRI -value pair.

The value takes an active context to be cleanly applied. and returns the corresponding inverse context .

  1. If Set element defaultLanguage to active context's default language if there is an array , process one; otherwise set it to @null .
  2. For each entry term definition in element recursively using this algorithm, passing a copy of the active context and perform the active property . following steps:
    1. If element has a single item and the compactArrays term's option IRI mapping is set to true , null continue with the compacted value is that item; otherwise next term definition .
    2. Set container to the compacted value is element . of the term's container mapping or @null if no such mapping exists.
    3. Otherwise, if If the term is a property generator , set element termType is an object: to propertyGenerators .
    4. If Otherwise set set element termType has an to @value term property or element is a node reference , return and append the result term to the term member of performing Value Compaction the JSON object on for the term's IRI in inverse context (append element term using active property . to inverseContext[iri]['term'] ).
    5. For each iri mapped to the term , perform the following steps:
      1. If the term has a type mapping to type , append the term to inverseContext[iri][container]['@type'][type][termType] , e.g., inverseContext['http://...']['@list']['@type']['http://...']['term'] .
      2. Otherwise, if the active property term has a @container language mapping store the associated language in language , replacing null with @null . Then append the term to @list inverseContext[iri][container]['@language'][language][termType] , e.g., inverseContext['http://...']['@list']['@language']['de']['term'] .
      3. Otherwise append the term to inverseContext[iri][container]['@null']['@null'][termType] as well as inverseContext[iri][container]['@language'][defaultLanguage][termType] to take the default language into consideration for terms without explicit language mapping .
  3. Remove all but the shortest and element has lexicographically least term in each term member in inverse context . The result is thus a corresponding single string value.
  4. Finally, sort the array associated with every @list propertyGenerators property, recursively compact member in inverse context lexicographically (shortest terms come first).

5.11 Inverse Context Query Algorithm

It is possible that property's value passing a copy multiple terms that differ in their container , type , or language mapping are mapped to the same IRI . The purpose of this algorithm is to query the active inverse context and to return either the active best matching term , or a list of potential property generators ensuring that the result is an array along with all null values removed. If there already exists a value for active term to fall back to if none of the property generators in can be applied.

This algorithm takes an element inverseContextSubtree , a queryPath and as generated by the full IRI of Compaction algorithm and a property level parameter which is also coerced initialized to @list , return an error. Otherwise store 0 if nothing else is passed. The algorithm returns either a string representing the resulting best matching term or a JSON object consisting of a propertyGenerators member, containing a sorted array as value of active potential property generators , and an optional term member containing a term to fall back to if empty or none of the property generators can be applied.

  1. Initialize result otherwise. to null .
  2. Otherwise, construct If output level as equals 3 , i.e., the deepest nested JSON object in the inverse context has been reached, perform the following steps:
    1. If inverseContextSubtree has a propertyGenerators member, copy that member into a new JSON object used for returning the result of compacting and store that object in element result . For each
    2. If property inverseContextSubtree has a term member and result is null , return the value of that member; otherwise result in is a JSON object , copy the term member into element: result and return result .
  3. If Otherwise, for each property entry is @id or of the array in queryPath's level'd position ( @type queryPath[level] ), perform the following steps:
    1. Set active property If inverseContextSubtree has no entry member, continue with the next entry .
    2. Otherwise set tmpResult to the result of performing IRI Compaction on recursively invoking this algorithm passing the property entry member of inverseContextSubtree as new inverseContextSubtree , queryPath , and level + 1 as new level .
    3. If value tmpResult is a string , the compacted and value result is the result of performing IRI Compaction on null , return value . Otherwise, tmpResult ; otherwise, if value result must is not null , transform tmpResult be to a JSON object whose propertyGenerators member is set to an empty array . Perform IRI Compaction on every entry of and whose term member is set to value tmpResult .
    4. If value result contains just one entry and is null , replace it with tmpResult .
    5. Otherwise, append each item of the compactArrays propertyGenerator option is set member of tmpResult to the true , propertyGenerator member of value result unless it is set to that entry. already in result's member. If result has no term member but tmpResult does, copy tmpResult's term member into result .
  4. Add Return result .

5.12 Value Compaction

Expansion transforms all values into expanded form in JSON-LD. This algorithm does the opposite, it compacts an algorithm according the term definition of the passed active property and . After the application of this algorithm a value is said to be in compacted form .

This algorithm takes a value to , an active context , an inverse context , an active property , and an optional output containerValue .

  1. Otherwise, If a value containerValue must has been passed, the active property has a container mapping set to @annotation and value be has an array . @annotation member which equals containerValue , remove that member.
  2. If value is empty: Set active property a JSON object to having a single member @id , return the result of performing IRI Compaction on property . that member's value.
  3. Create an entry in Otherwise, if output value for is a JSON object having a @value member, perform the following steps:
    1. If the active property has a type mapping and value . For each item in has a corresponding @type member, remove the @type member from value : .
    2. Set Otherwise, if the active property to the result of performing IRI Compaction has a language mapping for property and item using the active context . Compact item value by recursively performing this algorithm passing has a copy of the active context and corresponding @language member, remove the active property . @language member from value .
    3. If an entry already exists in Otherwise, if a output containerValue for has been passed, the active property , convert it to an array if necessary, has a container mapping set to @language , and append value has a @language member which equals containerValue , remove the compacted @language member from value .
    4. Otherwise, if the compacted active context has a default language
      1. and the value is not an array and active property has a corresponding @container mapping to @set @language or if member, remove the compactArrays option is set to false , convert @language member from value to an array. .
      2. Create an entry in Otherwise, or if the value of output value's for active property and @value member is a string , return value .
    5. If value has just a @value member, return the value of that member.
  4. Otherwise, return Return element value as the compacted element . is.

Issue 5.13 Perhaps this should also call Value Compaction on native types Find and strings, which could consolidate potential transformation in one place. Remove Property Generator Duplicates

If, after the This algorithm outlined above is run, the resulting checks if a specific value exists for all IRIs associated with a property generator and if so, it removes them. The algorithm takes five parameters: element is an array , property , value , active context , put active property .

  1. For each item element propertyGenerator into of the array which is the value of the @graph propertyGenerators property member of active property perform the following steps:
    1. Check that a new JSON object member exists for each IRI and then set associated with the element propertyGenerator . If value to is not null also check whether each of those members that JSON object . Finally, add a @context property to contains element and set it value . Values are considered to be equal if they are of the initially passed context . 4.9 Flattening Flattening is same type and have the process of taking a JSON-LD document, expanding same value(s); node objects it, labeling are considered to be equal if all members match, except if no @id member exists (i.e., it is an unlabeled nodes with a blank node , in that case node objects identifier, and returning an array of are never considered to be equal.
    2. If that's not the nodes defined in case, continue with the document. For example, assume next propertyGenerator .
    3. Otherwise, remove value from every member. If the following JSON-LD input document: { "@context": { "name": "http://xmlns.com/foaf/0.1/name", "knows": "http://xmlns.com/foaf/0.1/knows" }, "@id": "http://example.com/markus", "name": "Markus Lanthaler", "knows": { "name": "Manu Sporny" } } Running resulting value of a member is an empty array , remove the JSON-LD Flattening algorithm for member altogether from element .
    4. Return propertyGenerator .
  2. Return the value of the merged graph ( @merged term ) against the JSON-LD input document provided above would result in the following output: [ { "@id": "http://example.com/markus", "http://xmlns.com/foaf/0.1/knows": [ { "@id": "_:t0" } ], "http://xmlns.com/foaf/0.1/name": [ { "@value": "Markus Lanthaler" } ] }, { "@id": "_:t0", "http://xmlns.com/foaf/0.1/name": [ { "@value": "Manu Sporny" } ] } ] member of active property since no matching property generator has been found.

4.9.1 5.14 Flattening Algorithm

The algorithm takes two input variables, an element to flatten and the graph for which the node definitions should be returned. If a graph context is not set, it will default used to @merged which represents the result of merging all graphs including compact the default graph ( @default ). flattened document.

  1. Expand element according the Expansion Algorithm algorithm .
  2. Generate a nodeMap according the Node Map Generation Algorithm algorithm .
  3. Initialize Let defaultGraph be the value of the @default member of nodeMap ; a JSON object representing the default graph .
  4. For each other graphName - graph pair in nodeMap perform the following steps:
    1. If defaultGraph does not have a graphName member, create one and initialize its value to a JSON object consisting of an @id member whose value is set to graphName .
    2. Add a @graph member set to an empty array (referred to as result nodes ) to the JSON object which is the value of the graphName member of nodeMap .
    3. If For each nodeMap id has no property - node pair in graph , return ordered by result id , otherwise set add definitions node to its value. the nodes array .
  5. Foreach Initialize an empty array flattened.
  6. For each property id and - value node of of pair in definitions defaultGraph ordered by property : Add id , add value node to result flattened .
  7. If context equals null , return flattened .
  8. Return Otherwise, return the result of compacting flattened according the Compaction algorithm passing context ensuring that the compaction result . uses the @graph keyword (or its alias) at the top-level, even if the context is empty or if there is only one element to put in the @graph array . This ensures that the returned document has a deterministic structure.

4.9.2 5.15 Node Map Generation

The Node Map Generation This algorithm takes as input an expanded JSON-LD document and results in creates a JSON object nodeMap holding a flat an indexed representation of the graphs and nodes represented in the passed, expanded document. All nodes that are not uniquely identified by an IRI get assigned a (new) blank node identifier. identifier . The resulting nodeMap document will have a property member for every graph in the document whose value is another object with a property member for every node represented in the document. While the The default graph is stored under the @default property and the merged graph under the @merged property, member, all other graphs are stored under their respective IRIs . graph name.

The algorithm takes as input the an expanded JSON-LD document as element , the initially empty and a reference to a JSON object nodeMap , . Furthermore it has the optional parameters active graph (which defaults to @default as graph , null as list , ), an active subject , active property , and null a reference to a JSON object as id list . The nodeMap must be initialized to a JSON object consisting of a single member whose name corresponds with active graph and whose value is an empty JSON object .

  1. If element is an array, process each entry in element recursively, using this algorithm and return.
  2. If Otherwise element is not a JSON object or if it has a @value property, then if . Let list activeGraph be the JSON object which is not null , append element to the value of the active graph member of list and return. nodeMap .
  3. If id is null and if the it has a @id @type property exists and is an IRI , set member, perform for each id item to its value, otherwise set it to a blank node identifier created by the Generate Blank Node Identifier algorithm. following steps:
    1. If list item is not null a blank node identifier , append replace it with a new blank node reference to list using id as the value for @id . identifier .
    2. Let nodes be the value in nodeMap where the key is If graph activeGraph ; if has no such member item , create it and initialize its value exists, insert to a new JSON object for consisting of a single member @id with the key value graph item .
  4. If id element has an @value member, perform the following steps:
    1. If active property is not in nodes , create null , generate a new JSON object blank node with identifier id as the value for @id . Let and store node element be the as value of the member id in nodes activeGraph .

      Handling of free-floating values is still being discussed.

    2. For each property that is not @id and each Otherwise, if no value list in has been passed, merge element ordered by into the active property : member of the active subject in activeGraph .
    3. If Otherwise, append property element is to the @graph , recursively call this algorithm passing value for element , nodeMap , null for @list member of list and .
  5. Otherwise, if graph element is has an @merged @list use graph , otherwise use id for graph and then continue. member, perform the following steps:
    1. If Initialize a new JSON object property result is not @type and is having a keyword, merge single member property @list and whose value into node and then continue. is initialized to an empty array .
    2. For each Recursively call this algorithm passing the value of v element's in the array @list member as new value : If element and v result is a node definition or node reference : as list .
    3. If the active property @id is not an IRI or it does not exist, map v to a is null , new generate a blank node identifier name id to avoid collisions. If one does not already exist, add a node reference for and store v result into as value of the member node id for in property activeGraph .

      Handling of free-floating values is still being discussed.

    4. Recursively call this algorithm passing Otherwise, add v result for to the the value , nodeMap , graph , null of the active property for list , and name for member of the active subject in id activeGraph .
  6. Otherwise if v element has is a node object , perform the property following steps:
    1. If element has an @list @id then recursively call this algorithm with the member, store its value of @list as in element , id and remove the member from nodeMap , element . If graph , and id is a blank node identifier , replace it with a new array flattenedList blank node identifier .
    2. Otherwise generate a new blank node identifier and store it as list id . Create
    3. If activeGraph does not contain a member id , create one and initialize it to a new JSON object with the property consisting of a single member @list @id whose value is set to flattenedList and add it to node for property id .
    4. Otherwise, if If active property is @type and v is not an IRI null , generate perform the following steps:
      1. Create a new blank node identifier JSON object and add it to node reference for consisting of a single member @id whose value is property id .
      2. Otherwise, add If no v list to has been passed, merge node element for into the active property member of the active subject in activeGraph .
      3. Otherwise, append element to the @list member of list .
    5. After the above outlined algorithm
    6. If element has been executed, the node map for all graphs including an @type member, merge each value into the default graph are contained @type of active subject in nodeMap activeGraph . To also create the node map for the merged graph, execute Then remove the algorithm again, but pass @merged @type for member from graph element . 4.9.3 Generate Blank Node Identifier This algorithm is used by
    7. If element has an @annotation member, set the Node Map Generation Algorithm @annotation of active subject in activeGraph to deterministically name blank node its value. If such a member already exists in active subject identifiers. It uses and has a different value, raise a CONFLICTING_ANNOTATION error. Otherwise continue and remove the @annotation from identifier map element .
    8. If element and has an @graph member, recursively invoke this algorithm passing the value of the @graph member as new prefix element and takes a possibly null identifier and returns a id as new identifier based on active subject . Then remove the @graph member from prefix element . The variable
    9. Finally for each next identifier property is initialized to - prefix appended with 0 . The default value of pair in prefix element is _:t . ordered by property perform the following steps:
      1. If no property member exists in the old identifier is not null JSON object and which is in the identifier map , return the mapped identifier. Otherwise, if value of the old identifier is not null , create a new entry in identifier map id initialized to the current value member of next identifier . Increment next identifier activeGraph by adding one to the integer suffix. Return create the mapped identifier. member and initialize its value to an empty array .
      2. Otherwise, increment Recursively invoke this algorithm passing next identifier value by adding one to the integer suffix as new element , id as new active subject , and return its original value. property as new active property .

4.10 5.16 RDF Conversion Algorithms

A JSON-LD document may be converted between other RDF-compatible document formats using the algorithms specified in this section. The JSON-LD Processing Model This specification describes processing rules for extracting RDF from a algorithms to transform JSON-LD document, and for transforming documents to an array of Quad RDF quads retrieved by processing another serialization format into JSON-LD. and vice-versa. Note that many uses of JSON-LD may not require generation of RDF.

The processing algorithms described in this section are provided in order to demonstrate how one might implement a JSON-LD to RDF processor. Conformant implementations are only required to produce the same type and number of quads during the output process and but are not required to implement the algorithm exactly as described.

4.10.1 Overview This section is non-normative. JSON-LD is intended to have an easy to parse grammar that closely models existing practice in using JSON for describing object representations. This allows the use of existing libraries for parsing JSON. As with other grammars used for describing Linked Data , a key concept is that of a node in a linked data graph . Nodes may be of three basic types. The first is the IRI
, which is used to refer to node s in other linked data graph s. The second is the blank node , which are nodes for which an external name does not exist, or is not known. The third is a Literal , which express values such as strings, dates and other information having a lexical form, possibly including an explicit language or datatype. Data described with JSON-LD may be considered to be a graph made up of subject and object nodes related via a property node . Specific implementations may also choose to operate on the document as a normal JSON description of objects having attributes. Both approaches are valid ways to interact with JSON-LD documents.
4.10.2 Issue Parsing Examples This section is non-normative. The following examples show simple transformations of JSON-LD documents to Turtle [ TURTLE-TR ]. The first example uses a simple document containing a simple FOAF profile: { "@context": {"foaf": "http://xmlns.com/foaf/0.1/"}, "@id": "http://greggkellogg.net/foaf#me", "@type": "foaf:Person", "foaf:name": "Gregg Kellogg", "foaf:knows": { "@type": "foaf:Person", "foaf:name": "Manu Sporny" } } This translates fairly directly to a similar Turtle document: @prefix foaf: <http://xmlns.com/foaf/0.1/>. <http://greggkellogg.net/foaf#me> a foaf:Person; foaf:name "Gregg Kellogg"; foaf:knows [ a foaf:Person; foaf:name "Manu Sporny"]. The actual parsing steps first require that the JSON-LD document be expanded, to eliminate the @context : [{ "@id": "http://greggkellogg.net/foaf#me", "@type": ["http://xmlns.com/foaf/0.1/Person"], "http://xmlns.com/foaf/0.1/name": [{"@value": "Gregg Kellogg"}], "http://xmlns.com/foaf/0.1/knows": [{ "@type": ["http://xmlns.com/foaf/0.1/Person"], "http://xmlns.com/foaf/0.1/name": [{"@value": "Manu Sporny"}] }] }]
The process of translating this to RDF then operates over each node definition to find a subject, each property to find an RDF predicate , and each value of that property to find an object . In this case, each property has just a single object: foaf:name identifies a literal , and foaf:knows identifies a second node definition similar to Turtle's blankNodePropertyList . After expansion, JSON-LD numbers , booleans , typed literals , language-tagged-strings , and IRIs become explicit, and can be directly transformed into their RDF representations. [{ "@id": "http://greggkellogg.net/foaf#me", "@type": ["http://xmlns.com/foaf/0.1/Person"], "http://xmlns.com/foaf/0.1/name": [{"@value": "Gregg Kellogg"}], "http://xmlns.com/foaf/0.1/currentProject": [{"@id": "http://json-ld.org/"}], "http://xmlns.com/foaf/0.1/birthday": [{ "@value": "1957-02-27", "@type": "http://www.w3.org/2001/XMLSchema#date" }], "http://xmlns.com/foaf/0.1/knows": [{ "@type": ["http://xmlns.com/foaf/0.1/Person"], "http://xmlns.com/foaf/0.1/name": [{"@value": "Manu Sporny"}] }] }] Translates to:

This algorithm hasn't been updated yet.

@prefix foaf: <http://xmlns.com/foaf/0.1/>. @prefix xsd: <http://www.w3.org/2001/XMLSchema#>. <http://greggkellogg.net/foaf#me> a foaf:Person; foaf:name "Gregg Kellogg"; foaf:currentProject <http://json-ld.org/>; foaf:birthday "1957-02-27"^^xsd:date; foaf:knows [ a foaf:Person; foaf:name "Manu Sporny"].

4.10.3 5.16.1 Convert to RDF Algorithm

The algorithm below is designed for in-memory implementations with random access to JSON object elements.

A conforming JSON-LD processor implementing RDF conversion must implement a processing algorithm that results in the same set of RDF Quads quads that the following algorithm generates:

The algorithm takes four input variables: a element to be converted, an active subject , active property and graph name . To begin, the active subject , active property and graph name are set to null , and element is set to the result of performing the Expansion Algorithm on the JSON-LD input . which is expected to be a a well-formed JSON-LD document as defined in [ JSON-LD ]. This removes any existing context to allow the given context to be cleanly applied.

  1. If element is a JSON object , perform the following steps:
    1. Set active object to null .
    2. If element has a @value property:
      1. If the value of @value is a number , set the active object to a typed literal value using a string representation canonical lexical form of the value as defined in the section Data Round Tripping . Set datatype to the value of the @type property if it exists, otherwise either xsd:integer or xsd:double , depending on if the value contains a fractional and/or an exponential component.
      2. Otherwise, if the value of @value is true or false , set the active object to a typed literal value created from the string representation canonical lexical form of the value. Set datatype to the value of the @type property if it exists, otherwise xsd:boolean .
      3. Otherwise, if element contains a @type property, set the active object to a typed literal value .
      4. Otherwise, if element contains a @language property, set the active object to a language-tagged string .
      5. Otherwise, set the active object to a typed literal value using xsd:string as the datatype.
    3. If element has a @list property the value must be an array . Process its value as a list as described in List Conversion using the return value as the active object
    4. If active object is not null :
      1. If neither active subject nor active property are null , generate a Quad representing active subject , active property , active object , and graph name .
      2. Return active object .
    5. If element has a @id property, the value must be a string , set the active subject to the previously expanded value (either a blank node or an IRI ).
    6. Otherwise, if element does not have a @id property, set the active subject to newly generated blank node .
    7. Process each property and value in element , ordered by property , as follows:
      1. If property is @type , set the active property to rdf:type .
      2. Otherwise, if property is @graph , process value algorithm recursively, using active subject as graph name and null values for active subject and active property and then proceed to next property.
      3. Otherwise, if property is a keyword , skip this step.
      4. Otherwise, set active property to the expanded IRI value form of property .
      5. Process value recursively using this algorithm, passing copies of active subject , active property and graph name .
    8. Set active object to active subject .
  2. Otherwise, if element is an array , process each value in the array as follows, process element recursively using this algorithm, using copies of active subject , active property , and graph name .
  3. Otherwise, if element is a string , then the active property must be rdf:type so set the active object to an IRI .
  4. If any of these steps created an active object and neither active subject nor active property are null , generate a Quad using active subject , active property , active object and graph name .
  5. Return active object .

4.10.4 5.16.2 List Conversion

List Conversion is the process of taking an array of values and adding them to a newly created RDF Collection (see [ RDF-SCHEMA ]) by linking each element of the list using rdf:first and rdf:next , terminating the list with rdf:nil using the following sequence:

The algorithm is invoked with an array array , the active property and returns a value to be used as an active object in the calling location.

Note
This algorithm does not support lists containing lists.
Issue

This algorithm hasn't been updated yet.

  1. If array is empty return rdf:nil .
  2. Otherwise, generate a Quad using using the active subject , active property and a newly generated blank node identified as first blank node .
  3. For each element in array other than the last element:
    1. Create a processor state using first blank node as the active subject , and rdf:first as the active property .
      1. Process the value starting at Step 1 .
      2. Proceed using the previous processor state .
    2. Unless this is the last element in array , generate a new blank node identified as rest blank node , otherwise use rdf:nil .
    3. Generate a new Quad using first blank node , rdf:rest and rest blank node .
    4. Set first blank node to rest blank node .
    5. Return first blank node .

4.10.5 5.16.3 Convert from RDF Algorithm

In some cases, data exists natively in Triples the form of triples or Quads form; or quads ; for example, if the data was originally represented in an RDF graph or triple/quad store. This algorithm is designed to simply translate an array of Quads quads into a JSON-LD document.

When expanding typed literal values having a datatype of xsd:string , the @type must not be set to xsd:string and the resulting value must have only a @value property.

The conversion algorithm takes a single parameter input in the form of an array of Quad representations.

Issue

This algorithm hasn't been updated yet.

  1. Construct defaultGraph as a JSON object containing nodes and listMap , each an empty JSON object .
  2. Construct graphs as a JSON object containing defaultGraph identified by an empty string .
  3. For each quad in input :
    1. Set graph to the entry in graphs identified by name , initializing it to a new entry using the mechanism described in Step 1 .
    2. If property is rdf:first , use the entry in graph.listMap indexed by subject , initializing it to a new JSON object if nesessary. Represent object in expanded form, form , as described in Value Expansion . Add the resulting object representation to the entry indexed by first , and skip to the next quad. quad .
    3. If property is rdf:rest :
      1. If object is a blank node , use the entry in graph.listMap indexed by subject , initializing it to a new JSON object if necessary. Add the nominalValue of object to the entry indexed by rest .
      2. Skip to the next quad. quad .
    4. If name is not null , and defaultGraph.nodes does not contain an entry for name , create a new entry for name from a new JSON object with key/value pair of @id and a string representation of name . represented in expanded IRI form .
    5. Set value as the entry from graph.nodes for subject , initializing it to a new JSON object with key/value pair of @id and a string representation of subject represented in expanded IRI form if necessary.
    6. If property is rdf:type , object is not a JSON-LD value , and the useRdfType option is not present or false :
      1. Append the string representation of object represented in expanded IRI form to the array value for the key @type , creating an entry in value if necessary.
    7. If Otherwise, if object is a typed literal value and the useNativeTypes option is set to true :
      1. Generate a converted value :
        1. If the literal's type is xsd:boolean , the converted value is true if the literal matches the value true or false if the literal matches the value false .
        2. If the literal's type is xsd:integer or xsd:double , try to convert the literal to a JSON number . If the conversion is successful, store the result in converted value , otherwise set converted value to value .
        3. Otherwise, do not perform a conversion. Set the converted value to the value .
      2. Append the converted value to the array value for the key, creating an entry in value if necessary.
    8. Otherwise, if object is rdf:nil :
      1. Let key be the string representation of property . expressed in expanded IRI form .
      2. Append an empty @list representation to the array value for key , creating an entry in value if necessary.
    9. Otherwise,
      1. Let key be the string representation of property expressed in expanded IRI form and let object representation be object represented in expanded form as described in Value Expansion .
      2. If object is a blank node , use the entry in graph.listMap indexed by object , initializing it to a new JSON object if nesessary. Add an entry for head with object representation .
      3. Append object representation to the array value for key , creating an entry in value if necessary.
  4. For each name and graph in graphs :
    1. For each subject and entry in graph where entry has both head and first keys:
      1. Set value to the value of head in entry .
      2. Remove the entry for @id in value .
      3. Add an entry to value for @list initialized to a new array containing the value of first from entry .
      4. While entry has a key for rest :
        1. Set entry to the value of graph.listMap for entry.rest .
        2. Add the value for entry.first to the list array.
  5. Create array as an empty array .
  6. For each subject and entry in defaultGraph.nodes ordered by subject :
    1. Add entry to array .
    2. If graphs has an entry for subject , add a property @graph in entry containing the ordered entries from graphs[subject].nodes .
  7. Return array as the result.

5. 5.16.4 Data Round Tripping

When converting JSON-LD to RDF JSON-native types such as numbers and booleans are automatically coerced to xsd:integer , xsd:double , or xsd:boolean . Implementers must ensure that the result is a in canonical lexical form in the form of a string . A canonical lexical form is a set of literals from among the valid set of literals for a datatype such that there is a one-to-one mapping between the canonical lexical form and a value in the value space as defined in [ XMLSCHEMA11-2 ]. In other words, every value must be converted to a deterministic string representation.

The canonical lexical form of an integer , i.e., a number without fractions or a number coerced to xsd:integer , is a finite-length sequence of decimal digits ( 0-9 ) with an optional leading minus sign; leading zeroes are prohibited. To convert the number in JavaScript, implementers can use the following snippet of code:

Example 25 12
(value).toFixed(0).toString()

The canonical lexical form of a double , i.e., a number with fractions or a number coerced to xsd:double , consists of a mantissa followed by the character "E", followed by an exponent. The mantissa must be a decimal number. The exponent must be an integer. Leading zeroes and a preceding plus sign ( + ) are prohibited in the exponent. If the exponent is zero, it must be indicated by E0 . For the mantissa, the preceding optional plus sign is prohibited and the decimal point is required. Leading and trailing zeroes are prohibited subject to the following: number representations must be normalized such that there is a single digit which is non-zero to the left of the decimal point and at least a single digit to the right of the decimal point unless the value being represented is zero. The canonical representation for zero is 0.0E0 . xsd:double 's value space is defined by the IEEE double-precision 64-bit floating point type [ IEEE-754-1985 ]; in JSON-LD the mantissa is rounded to 15 digits after the decimal point.

To convert the number in JavaScript, implementers can use the following snippet of code:

Example 26 13
(value).toExponential(15).replace(/(\d)0*e\+?/,'$1E')
Note

When data such as decimals need to be normalized, JSON-LD authors should not use values that are going to undergo automatic conversion. This is due to the lossy nature of xsd:double values. Authors should instead use the expanded object form to set the canonical lexical form directly.

The canonical lexical form of the boolean values true and false are the strings true and false .

When JSON-native number s, are type coerced, lossless data round-tripping can not be guaranted as rounding errors might occur. Additionally, only literals typed as xsd:integer , xsd:double , and xsd:boolean are automatically converted back to their JSON-native counterparts in when converting from RDF .

Note

Some JSON serializers, such as PHP's native implementation in some versions, backslash-escape the forward slash character. For example, the value http://example.com/ would be serialized as http:\/\/example.com\/ . This is problematic as other JSON parsers might not understand those escaping characters. There is no need to backslash-escape forward slashes in JSON-LD. To aid interoperability between JSON-LD processors, a JSON-LD serializer must not backslash-escape forward slashes.

6. The Application Programming Interface

This API provides a clean mechanism that enables developers to convert JSON-LD data into a a variety of output formats that are easier to work with in various programming languages. If a JSON-LD API is provided in a programming environment, the entirety of the following API must be implemented.

6.1 JsonLdProcessor

The JSON-LD processor interface is the high-level programming structure that developers use to access the JSON-LD transformation methods.

The JSON-LD API signatures are the same across all programming languages. Due to the fact that asynchronous programming is uncommon in certain languages, developers may implement a processor with a synchronous interface instead. In that case, the callback parameter must not be included and the result must be returned as a return value instead.

It is important to highlight that conformant JSON-LD processors must not modify the input parameters.

[Constructor]
interface JsonLdProcessor {
    void expand ((object or object[] or DOMString) input, JsonLdCallback callback, optional JsonLdOptions? options);    void compact ((object or object[] or DOMString) input, (object or DOMString) context, JsonLdCallback callback, optional JsonLdOptions? options);    void flatten ((object or object[] or DOMString) input, (object or DOMString)? context, JsonLdCallback callback, optional JsonLdOptions? options);
};

6.1.1 Methods

compact
Compacts the given input using the context according to the steps in the Compaction Algorithm .
Parameter Type Nullable Optional Description
input ( object or object[] or DOMString ) The JSON-LD object or array of JSON-LD objects to perform the compaction upon or an IRI referencing the JSON-LD document to compact.
context ( object or DOMString ) The context to use when compacting the input ; either in the form of an JSON object or as IRI .
callback JsonLdCallback A callback that is called when processing is complete on the given input .
options JsonLdOptions A set of options to configure the used algorithms such. This allows, e.g., to set the input document's base IRI . This also includes the optimize flag, which, if set, will allow processor-specific optimization.
Return type: void
expand
Expands the given input according to the steps in the Expansion Algorithm .
Parameter Type Nullable Optional Description
input ( object or object[] or DOMString ) The JSON-LD object or array of JSON-LD objects to perform the expansion upon or an IRI referencing the JSON-LD document to expand.
callback JsonLdCallback A callback that is called when processing is complete on the given input .
options JsonLdOptions A set of options to configure the used algorithms such. This allows, e.g., to set the input document's base IRI .
Return type: void
flatten
Flattens the given input and compacts it using the passed context according to the steps in the Flattening Algorithm .
Parameter Type Nullable Optional Description
input ( object or object[] or DOMString ) The JSON-LD object or array of JSON-LD objects or an IRI referencing the JSON-LD document to flatten.
context ( object or DOMString ) The context to use when compacting the flattened input ; either in the form of an JSON object or as IRI . If null is passed, the result will not be compacted but keept in expanded form.
callback JsonLdCallback A callback that is called when processing is complete on the given input .
options JsonLdOptions A set of options to configure the used algorithms such. This allows, e.g., to set the input document's base IRI .
Return type: void

6.2 Callbacks

JSON-LD processors utilize callbacks in order to return information in an asynchronous manner to calling applications. This section details the parameters sent to those callbacks.

6.2.1 JsonLdCallback

The JsonLdCallback is called when processing of an API method of JsonLdProcessor has been completed successfully or been terminated by an error.


callback

JsonLdCallback

=

void

(

JsonLdProcessingError

error
,
object
or
object

[]

document

);
Callback JsonLdCallback Parameters
error of type JsonLdProcessingError
If the value is null , then no error occurred. If the value is non- null , a processing error occurred and the details will be contained within the error object.
document of type array of object or object
The processed JSON-LD document.

6.3 Data Structures

This section describes datatype definitions used within the JSON-LD API.

6.3.1 JsonLdOptions

The JsonLdOptions type is used to pass various options to the JsonLdProcessor methods.

dictionary JsonLdOptions {    DOMString           base;    object or DOMString expandContext = null;    boolean             compactArrays = true;    boolean             optimize = false;    boolean             useRdfType = false;    boolean             useNativeTypes = true;
};
Dictionary JsonLdOptions Members
base of type DOMString
The Base IRI to use when expanding the document. This overrides the value of input if it is a IRI . If not specified and input is not an IRI , the base IRI defaults to the current document IRI if in a browser context, or the empty string if there is no document context.
compactArrays of type boolean , defaulting to true
If set to true , the JSON-LD processor replaces arrays with just one element with that element during compaction. If set to false , all arrays will remain arrays even if they have just one element.
expandContext of type object or DOMString , defaulting to null
A context that is used to initialize the active context when expanding a document.
optimize of type boolean , defaulting to false
If set to true , the JSON-LD processor is allowed to optimize the output of the Compaction Algorithm to produce even compacter representations. The algorithm for compaction optimization is beyond the scope of this specification and thus not defined. Consequently, different implementations may implement different optimization algorithms.
useNativeTypes of type boolean , defaulting to true
If set to true , the JSON-LD processor will try to convert typed values to JSON native types instead of using the expanded object form when converting from RDF . xsd:boolean values will be converted to true or false . xsd:integer and xsd:double values will be converted to JSON numbers .
useRdfType of type boolean , defaulting to false
If set to true , the JSON-LD processor will use the expanded rdf:type IRI as the property instead of @type when converting from RDF .

6.3.2 JsonLdProcessingError

Developers should note that the details of error handling are being actively debated.

The JsonLdProcessingError type is used to report errors to a JsonLdCallback .

dictionary JsonLdProcessingError {    JsonLdErrorCode code;    DOMString?      message;
};
Dictionary JsonLdProcessingError Members
code of type JsonLdErrorCode
a string representing the particular error type, as described in the various algorithms in this document.
message of type DOMString , nullable
an optional error message containing additional debugging information. The specific contents of error messages are outside the scope of this specification and thus implementation dependent.

6.3.3 JsonLdErrorCode

The JsonLdErrorCode represent the collection of valid JSON-LD error codes.

enum JsonLdErrorCode {
    "INVALID_SYNTAX",
    "LOAD_ERROR",
    "LIST_OF_LISTS_DETECTED"
};
Enumeration description
INVALID_SYNTAX A violation of the grammar as defined by the JSON-LD syntax specification [ JSON-LD ] was detected.
LOAD_ERROR There was a problem encountered loading a remote context.
LIST_OF_LISTS_DETECTED A list of lists was detected. List of lists are not supported in this version of JSON-LD due to the algorithmic complexity associated with conversion to RDF.

A. Acknowledgements

A large amount of thanks goes out to the JSON-LD Community Group participants who worked through many of the technical issues on the mailing list and the weekly telecons - of special mention are Niklas Lindström, François Daoust, Lin Clark, and Zdenko 'Denny' Vrandečić. The editors would like to thank Mark Birbeck, who provided a great deal of the initial push behind the JSON-LD work via his work on RDFj. The work of Dave Lehn and Mike Johnson are appreciated for reviewing, and performing several implementations of the specification. Ian Davis is thanked for this his work on RDF/JSON. Thanks also to Nathan Rixham, Bradley P. Allen, Kingsley Idehen, Glenn McDonald, Alexandre Passant, Danny Ayers, Ted Thibodeau Jr., Olivier Grisel, Josh Mandel, Eric Prud'hommeaux, David Wood, Guus Schreiber, Pat Hayes, Sandro Hawke, and Richard Cyganiak for or their input on the specification.

B. References

B.1 Normative references

[BCP47] A. Phillips; M. Davis. Tags for Identifying Languages September 2009. IETF Best Current Practice. URL: http://tools.ietf.org/html/bcp47
[IEEE-754-1985]
IEEE. IEEE Standard for Binary Floating-Point Arithmetic. See http://standards.ieee.org/reading/ieee/std_public/description/busarch/754-1985_desc.html
[JSON-LD]
The JSON-LD Syntax Manu Sporny, Gregg Kellogg, Markus Lanthaler Editors. World Wide Web Consortium (work in progress). 22 May 2012. Editor's Draft. This edition of the JSON-LD Syntax specification is http://json-ld.org/spec/ED/json-ld-syntax/20120522/. The latest edition of the JSON-LD Syntax is available at http://json-ld.org/spec/latest/json-ld-syntax/
[JSON-POINTER] JSON Pointer P. Bryan, Ed. IETF Draft. URL: http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-02
[RDF-CONCEPTS]
RDF 1.1 Concepts and Abstract Syntax Richard Cyganiak, David Wood, Editors. World Wide Web Consortium (work in progress). 30 May 2012. Editor's Draft. This edition of the JSON-LD Syntax specification is http://www.w3.org/TR/2011/WD-rdf11-concepts-20110830/. The latest edition of the JSON-LD Syntax is available at http://www.w3.org/TR/rdf11-concepts/
[RDF-SCHEMA]
Dan Brickley; Ramanathan V. Guha. RDF Vocabulary Description Language 1.0: RDF Schema. 10 February 2004. W3C Recommendation. URL: http://www.w3.org/TR/2004/REC-rdf-schema-20040210
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[RFC3986]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifier (URI): Generic Syntax. January 2005. Internet RFC 3986. URL: http://www.ietf.org/rfc/rfc3986.txt
[RFC3987]
M. Dürst; M. Suignard. Internationalized Resource Identifiers (IRIs). January 2005. Internet RFC 3987. URL: http://www.ietf.org/rfc/rfc3987.txt
[RFC4627]
D. Crockford. The application/json Media Type for JavaScript Object Notation (JSON) July 2006. Internet RFC 4627. URL: http://www.ietf.org/rfc/rfc4627.txt
[WEBIDL]
Web IDL Cameron McCormack, Editor. World Wide Web Consortium. 19 April 2012. Candidate Recommendataion. This edition of Web IDL is http://www.w3.org/TR/2012/CR-WebIDL-20120419/. The latest edition of Web IDL is available at http://dev.w3.org/2006/webapi/WebIDL/
[XMLSCHEMA11-2]
Henry S. Thompson; et al. W3C XML Schema Definition Language (XSD) 1.1 Part 2: Datatypes. 5 April 2012. W3C Recommendation URL: http://www.w3.org/TR/2012/REC-xmlschema11-2-20120405/

B.2 Informative references

[BCP47]
A. Phillips; M. Davis. Tags for Identifying Languages September 2009. IETF Best Current Practice. URL: http://tools.ietf.org/html/bcp47
[ECMA-262]
ECMAScript Language Specification. June 2011. URL: http://www.ecma-international.org/publications/standards/Ecma-262.htm
[JSON-LD-TESTS]
JSON-LD Test Suite (work in progress).
[TURTLE-TR]
Eric Prud'hommeaux, Gavin Carothers. Turtle: Terse RDF Triple Language. 09 August 2011. W3C Working Draft. URL: http://www.w3.org/TR/2011/WD-turtle-20110809/ [UNICODE] The Unicode Consortium. The Unicode Standard. 2003. Defined by: The Unicode Standard, Version 4.0 (Boston, MA, Addison-Wesley, ISBN 0-321-18578-1), as updated from time to time by the publication of new versions URL: http://www.unicode.org/unicode/standard/versions/enumeratedversions.html