Data JSON - Documentation

Questions ou commentaires?

Needs translation

Purpose

Insert content extracted from a JSON file or provided by a dataset.

The role of this plugin is to display selected data into HTML elements, if you need to manipulate the data prior it get displayed or you need to interact with, then use this plugin in conjonction with the JSON-manager plugin that support dataset.

Use when

When you need to display the same atomic information on multiple pages. Like a fee for a services that is re-use across multiple pages.

To insert repeatitive content by using HTML5 template element.

Do not use when

  • To insert block of HTML content, instead use data-ajax with the filtering option if neccessary.
  • For inserting data that only apply to an unique page.

Working example

English:

French:

Evaluation and report

How to implement

  1. Create a valid JSON file
  2. The one of the following:
    • Add one of the following data-json attributes to an element, with the attribute value being the URL of the JSON file followed by a JSON Pointer (RFC6901) URL hash:

      • data-json-after: Insert content after the element

        <span data-json-after="json/data-en.json#/JSON/Pointer">
        			...
        		</span>
      • data-json-append: Insert content at the end of the element

        <span data-json-append="json/data-en.json#/JSON/Pointer">
        			...
        		</span>
      • data-json-before: Insert content before the element

        <span data-json-before="json/data-en.json#/JSON/Pointer">
        			...
        		</span>
      • data-json-prepend: Insert content at the start of the element

        <span data-json-prepend="json/data-en.json#/JSON/Pointer">
        			...
        		</span>
      • data-json-replace: Replace content inside the element

        <span data-json-replace="json/data-en.json#/JSON/Pointer">
        			...
        		</span>
      • data-json-replacewith: Replace the element by the content

        <span data-json-replacewith="json/data-en.json#/JSON/Pointer">
        			...
        		</span>
    • For HTML5 templating, add the attribute data-wb-json on the elements you wanted to append items. The following populate a list:

      <ul data-wb-json='{
      		"url": "data-en.json#/anArray",
      		"queryall": "li",
      		"mapping": [
      			"/name"
      		]
      	}'>
      	<template>
      		<li></li>
      	</template>
      </ul>

      Where:

      url
      JSON file location or dataset name followed by an optional JSON pointer
      queryall
      Contain a valid CSS selector.
      mapping
      Array of JSON pointer, as many as the return result of queryall applied on the <template> element.

      Note: When using the template for filling a table, wrap your rows template into a table element in order to avoid a bug in Internet Explorer.

    • Use the data for shapping multiple area of an HTML element

      <a href="generic/location.html" data-wb-json='[
      		{
      			"url": "mydata.json#/first/title",
      			"type": "replace"
      		},
      		{
      			"url": "mydata.json#/first/html_url",
      			"type": "prop",
      			"prop": "href"
      		}
      	]'>Generic location</a>

Selecting data

(Source: JSON Pointer, RCF6901)

For example, given the JSON document

{
	"foo": ["bar", "baz"],
	"": 0,
	"a/b": 1,
	"c%d": 2,
	"e^f": 3,
	"g|h": 4,
	"i\\j": 5,
	"k\"l": 6,
	" ": 7,
	"m~n": 8
}

The following URI fragment identifiers evaluate to the accompanying values:

URI fragment Returning value
# The whole document
#/foo ["bar", "baz"]
#/foo/0 "bar"
#/ 0
#/a~1b 1
#/c%25d 2
#/e%5Ef 3
#/g%7Ch 4
#/i%5Cj 5
#/k%22l 6
#/%20 7
#/m~0n 8

Issue that you may encounter

Display nothing, plugin seems to be broken.
Ensure that your JSON file is valid
Recently updated data do not display
Refresh your browser cache by opening a new tab the JSON file and then do a hard refresh Ctrl + F5 or by testing your page from a new private mode session of your browser.

HTML5 template element in the specification

Official reference:

The following was extracted from HTML5.2 spec:

Contexts in which this element can be used.

The following is a non-normative description of where the element can be used. This information is redundant with the content models of elements that allow this one as a child, and is provided only as a convenience.

Content model

A normative description of what content must be included as children and descendants of the element.

Note that the following elements, incomplete list, have a content model that could expect script-supporting elements: ol, ul, dl, table, thead, tbody, tfoot, tr, select, menu

Template - Transforming JSON object into an array

Since WET 4.0.27 or without the streamline flag since WET 4.0.64 it is possible to iterate anything that is not an array to render content through a <template>. It simply get transformed into a array. There is a low risk of lost of information, only one specific use case. It's quite similar to the JSON-LD Expanded Form. In this transformation process, it assume the array key is an IRI. Then the will result include some property from JSON-LD such as @id and @value. The @id wont be overwritten, in those such case the array key will be discard after the transformation.

When the value is a sub-object

Source

{
	"key1": {
		"keyA": "value1",
		"keyB": "value2"
	},
	"key2": {
		"keyA": "value3",
		"keyB": "value4"
	}
}

After

[
	{
		"@id": "key1",
		"keyA": "value1",
		"keyB": "value2"
	},
	{
		"@id": "key2",
		"keyA": "value3",
		"keyB": "value4"
	}
]

When the value are not an object

Source

{
	"key1": "value1",
	"key2": "value2",
	"key3": "value3"
}

After

[
	{
		"@id": "key1",
		"@value": "value1"
	},
	{
		"@id": "key2",
		"@value": "value2"
	},
	{
		"@id": "key3",
		"@value": "value3"
	}
]

When the value is a native data type

Selecting the value of key1 to iterate.

Source

{
	"key1": "value1"
}

After

{
	"key1": [
		"value1"
	]
}

When the value is an array

Source

{
	"key1": [
		{ "keyA": "value1" },
		{ "keyA": "value2" }
	],
	"key2":  [
		{ "keyA": "value3" },
		{ "keyA": "value4" }
	]
}

After

[
	{
		"@id": "key1",
		"@value": [
			"keyA": "value1",
			"keyA": "value2"
		]
	},
	{
		"@id": "key2",
		"@value":
			"keyA": "value3",
			"keyA": "value4"
		]
	}
]

When the array key information will be lost

Because the object already contains a field named @id

Source

{
	"key1": {
		"@id": "https://wet-boew.github.io/vocab/example/1",
		"keyA": "value1",
		"keyB": "value2"
	},
	"key2": {
		"@id": "https://wet-boew.github.io/vocab/example/2",
		"keyA": "value3",
		"keyB": "value4"
	}
}

After

[
	{
		"@id": "https://wet-boew.github.io/vocab/example/1",
		"keyA": "value1",
		"keyB": "value2"
	},
	{
		"@id": "https://wet-boew.github.io/vocab/example/2",
		"keyA": "value3",
		"keyB": "value4"
	}
]

Cache busting

Before to use the cache busting mechanism with your data json instance, it's highly recommended to configure your server properly instead.

Various strategy can be set on the server side and those are communicated to the browser through an http header as defined in section 5 of RFC7234.

Test functions that extract a testable value

Those test require a data pointer either provided with the value property which would also iterate or with assess which don't iterate.

fn:isArray
Boolean returning if the tested value is an array or not.
fn:isLiteral
Boolean returning if the tested value is an literal or not. A literal value is considered to be defined and not an object.
fn:getType
Return type of the value set via the @type property or its corresponding javascript typeof value.
fn:guessType

The template parser will try to guess the data type of the tested value.

This test function will return:

  • rdfs:Container when the value is an array.
  • rdfs:Literal for any value that is literal. A literal value is considered to be defined and not an object.
  • rdfs:Resource when the value is an JSON object without any defined type.
  • xsd:anyURI when the value is a string which start with non-spaced letter and digit immediately followed by colon ":" like https://example.com
  • xsd:string when the value is a string and don't look to be an URI.
  • xsd:boolean when the value is a boolean with the value set to true or false
  • xsd:double when the value is a JSON number
  • The value set via the @type sub property
  • undefined when the value is undefined
fn:getValue
Return value as the testable value.

Operand function

Operand functions that check the testable value.

softEq (default)
Check if the value is equivalent equal to the expectation optionally either in an array value. When no expectation provide, return true if the testable value exist.
eq
Check if the value equal the expectation. Including when the value is an object.
neq
Check if the value is not equal the expectation. Including when the value is an object.
in
Check if the value (or array of value) is in the expectation (or array of expectation)
nin
Check if the value (or array of value) is not in the expectation (or array of expectation)

Configuration options

Option Description How to configure Values
Insertion type Configure the origin and destination of the content to be extracted from a JSON file. Add the configuration attribute to the affected element with the value being the URL followed by a JSON pointer hash of the data to be inserted.
data-json-after:
Insert content after the element
data-json-append:
Insert content at the end of the element
data-json-before:
Insert content before the element
data-json-prepend:
Insert content at the start of the element
data-json-replace:
Replace content inside the element
data-json-replacewith:
Replace the element by the content
url Required. Define the url or the dataset name to use. When used in a template mode, the URL should point to an array object. You can follow the url or the dataset name by a JSON Pointer (RFC6901).
data-wb-json='{ "url": "location/of/json/file.json#/" }'
The url are a json file
data-wb-json='{ "url": "[datasetName]#/" }'
The url is a reference to a dataset managed by a json-manager defined in the page
type Configure the origin and destination of the content to be extracted from a JSON file. Similar of using the insertion type. Add a value to type that is recongnized, if leaved it it will assume it's means template.
template
(Default) Apply the HTML template by using the json.
addclass
Add a class to the element
after
Insert content after the element
append
Insert content at the end of the element
attr
Change an attribute on the element. It's require also the configuration attr which contain the attribute name.
before
Insert content before the element
removeclass
Remove a class to the element
replace
Replace content inside the element
replacewith
Replace the element by the content
prepend
Insert content at the start of the element
prop
Change a property on the element. It's require also the configuration prop which contain the attribute name.
val
Set a value on an input element.
attr Specify the element attribute name. Only required when type="attr". data-wb-json='{ "url": "", "type": "attr", "attr": "href" }' A valid attribute name supported by the element and be one of the following href, src, data-*, aria-*, role, pattern, min, max, step, low, high, lang, hreflang, action.
prop Specify the element attribute name. Only required when type="prop". data-wb-json='{ "url": "", "type": "prop", "prop": "disabled" }' A valid attribute considered as a propperty supported by the element and be one of the following checked, selected, disabled, required, readonly, multiple, hidden.
queryall Template only. Selects elements inside the cloned template. It's assumed the mapping represent the number of returned results of this query. data-wb-json='{ "url": "", "queryall": "li" }' Contain a valid CSS selector.
tobeclone Template only. Selects an elements inside the template that will be cloned for the mapping and the insertion. It's assumed the mapping represent the number of returned results of this query. When it's specified, this returning value is considered as the root of the mapping object selector and for the queryall options. data-wb-json='{ "url": "", "queryall": "li" }'
Default
All the children elements of the source template
If defined
A valid CSS selector.
filter Deprecated

Use the filtering feature from the JSON manager instead.

Template only. Validating for truthness to allow array items to be processed by the template. Contains an array of evaluation criteria for array items.

data-wb-json='{ "url": "", "filter": [ {evaluation object} ] }' Evaluation object have the following property
path
Required. JSON pointer to the data being evaluated
value
Required. Value of witch the data would be evaluated
optional
Indicated if the evaluation is optional.
Evaluation object path Deprecated

Use the filtering feature from the JSON manager instead.

Template only, for evaluation object and required. JSON pointer to the data being evaluated. It's must start with an "/".

data-wb-json='{ "url": "", "filter": [ { "path": "/JSON Pointer" } ] }' A valid JSON Pointer (RFC6901)
Evaluation object value Deprecated

Use the filtering feature from the JSON manager instead.

Template only, for evaluation object and required.

data-wb-json='{ "url": "", "filter": [ { "value": "A value" } ] }' Any value that could be compared with the information retreived form the path.
Evaluation object optional Deprecated

Use the filtering feature from the JSON manager instead.

Template only and for evaluation object.

data-wb-json='{ "url": "", "filter": [ { "optional": true } ] }' True or false. If omited it will be false by default.
filternot Deprecated

Use the filtering feature from the JSON manager instead.

Template only. Validating for falsness to disallow an array items to be processed by the template. Contains an array of evaluation criteria for array items.

data-wb-json='{ "url": "", "filternot": [ {evaluation object} ] }' Evaluation object have the following property
path
Required. JSON pointer to the data being evaluated
value
Required. Value of witch the data would be evaluated
optional
Indicated if the evaluation is optional.
source Template only. Pointer to the template elements. Not required when the template is the child of the host element. data-wb-json='{ "url": "", "source": "#idToMyTemplate" }' JQuery selector that represent the template element on the current page.
streamline Template only. Indicate not to initiate the process of iterating the data and instead execute the mapping object directly data-wb-json='{ "url": "", "streamline": true|false }' JQuery selector that represent the template element on the current page.
mapping Template only. Array of string represeting a JSON pointer or object where it specify how to bind the data with the template content. If the configuration queryall is used, the number of items in the mapping must match the number of returning result of the queryall. In the other hand, if queryall configuration is not specified, than each mapping object must define a selector configuration. data-wb-json='{ "url": "", "mapping": [ "JSON Pointer", "JSON Pointer" ] }' or data-wb-json='{ "url": "", "mapping": [ {mapping object}, {mapping object} ] }'

When queryall is not specified, it's is an array of string with a the JSON pointer. (Equivalent to the value in the Mapping object)

A mapping object can contain another mapping object to support sub-template. That inner mapping can also contain it's own queryall configuration.

When its value is explicitly set to null, the associated template object won't be used to map data.

Mapping object selector Template only, for mapping object and required when queryall is not specified. Should selects one element inside the cloned template. When selecting an array, that allow you run sub-template. To configure a sub-template, the mapping object is extended like: you can optionnaly set the "source" configuration, optionnaly set the "queryall" configuration and you can also set a inner "mapping" object for the mapping of the sub-template. data-wb-json='{ "url": "", "mapping": [ { "selector": "A CSS Selector" } ] }' A valid CSS selector.
Mapping object value Template only, for mapping object and required when queryall is not specified. JSON Pointer representing the data to be mapped. data-wb-json='{ "url": "", "mapping": [ { "value": "A JSON Pointer" } ] }' A valid JSON Pointer (RFC6901)
Mapping object placeholder Template only, for mapping object and optinal when queryall is not specified. String representing the placeholder to replace by the selected data data-wb-json='{ "url": "", "mapping": [ { "placeholder": "" } ] }' A findable string in the selected element in the template.
Mapping object attr Template only, for mapping object and optional when queryall is not specified. Name of an attribute where the selected data will replace his value. data-wb-json='{ "url": "", "mapping": [ { "attr": "href" } ] }' A valid attribute of the selected element.
Mapping object isHTML Template only, for mapping object and optional when queryall is not specified. Flag indicating if the content to be mapped is a string HTML. data-wb-json='{ "url": "", "mapping": [ { "isHTML": "true" } ] }' A valid attribute of the selected element.
Mapping object test Test functions that extract a testable value. It requires a JSON pointer provided by either the mapping property assess or value. data-wb-json='{ "url": "", "mapping": [ { "test": "Test-Technical-Name" } ] }' A valid technical test name like fn:guessType. See the predefined list of test function
Mapping object assess (JSON Pointer) This the value to take for performing the conditional evaluation. Alternatively, it will take the value from the value property. Another difference is the assess would not be iterated compared to value which would be iterated for the inner mapping. data-wb-json='{ "url": "", "mapping": [ { "assess": "A JSON Pointer", "test": "Test-Technical-Name" } ] }' A valid JSON Pointer (RFC6901)
Mapping object expect The value which is going to be compared by the operand. If not provided it will use the trueness state of the testable value return by the test function. data-wb-json='{ "url": "", "mapping": [ { "expect": "A value", "assess": "A JSON Pointer", "test": "Test-Technical-Name" } ] }' A string or an JSON object use for comparison by the operand.
Mapping object operand Operand functions that evaluate the testable value against the expected value. data-wb-json='{ "url": "", "mapping": [ { "operand": "Operand-Technical-Name", "assess": "A JSON Pointer", "test": "Test-Technical-Name" } ] }' A valid operand name like fn:eq. See the predefined list of operand function
Mapping object @type Mapping function to use in order to process the data and the configuration. data-wb-json='{ "url": "", "mapping": [ { "@type": "rdf:Alt", "mapping": [ ... ] } ] }'
rdf:Alt
Allow to configure a list of mapping where it's going to execute only the first children passing its test condition. The rdf:Alt type require the mapping property mapping.
Mapping object append Force the content created via the template to be append from the template parent element instead of being inserted in-place. data-wb-json='{ "url": "", "mapping": [ { "append": "true" } ] }' Boolean indicating if the content need to be append.
Mapping object encode Indicate to encode the content if its type is rdf:HTML data-wb-json='{ "url": "", "mapping": [ { "encode": true|false } ] }' Boolean indicating if the content need to be encoded when the id reference are followed.
appendto Template only. When the elements are outside the editing area, this specified the element to use to append the template. Specifying the data-json directly of the elements should remain how it is used. Note: Since WET 4.0.27 a bug fix has change the behavior of one usecase depending how the mapping is configured. Since WET 4.0.27, using the data-json template is always done against an JSON array. data-wb-json='{ "url": "", "appendto": "title" }' A valid jQuery selector.
nocache Prevent caching. Prior using the functionality, use the various caching strategies that can be set and communicated through http header from your server, as defined in section 5 of RFC7234. Also, please note that some server may not like to have an query appended to his url and you may get an HTTP error like "400 Bad Request" or "404 Not Found". Like a page served by a domino server will return 404 error if the query string do not start with "?open", "?openDocument" or "?readForm". data-wb-json='{ "url": "", "nocache": true }' or data-wb-json='{ "url": "", "nocache": "nocache" }'
Default
The browser will manage the cache based on how the server has sent the file.
true
Boolean, Use the same cache buster id for the user session. Clossing and opening the tab should generate a new cache busting id.
nocache
String, A new id is generated everytime the file is fetched
nocachekey Prevent caching. Optional, it defined what query parameter name to use for the cache busting. data-wb-json='{ "url": "", "nocache": true, "nocachekey": "wbCacheBust" }'
Default
Will use "wbCacheBust" for the parameter name.
String
URL pre-encoded string
data Add parameter in the request body. data-wb-json='{ "url": "", "data": { "prop": "value" } }' or data-wb-json='{ "url": "", "data": "prop=value" } }'
Default
No data are sent in the request body
String
The value is sent as is in the request body
Javascript Object
The value is stringify before to be added to the request body
contenttype Set the content type of the request body when data are sent data-wb-json='{ "url": "", "contenttype": "text/turtle", "data": "" }'
Default
When data is added, application/json
String
A valid content type as defined in the IANA media type registry.
method Set the HTTP method to be use when fetching the resource. data-wb-json='{ "url": "", "data": "", "method": "PUT" }'
Default (no data)
The method is "GET".
Default (with data)
The method is "POST".
String
A valid method allowed by the browser.
trigger Initiate WET features for the content rendered with a template. data-wb-json='{ "url": "", "trigger": true }'
false (default):
Content is kept as is.
true:
Will initiate any WET feature on rendered content
fail Configuration and mapping instruction to follow when fetching a JSON do fail. data-wb-json='{ "url": "", "fail": { "template": <See template config>, "mapping": <See mapping config> } }'

The configuration template and mapping must be defined if a failure condition is defined.

The following static content object can be mapped:

{
	error: "<Details of the error in English>",
	status: "<Status or category of the error>",
	url: "<Relative URL of the failed resource>",
	response: {
		text: "<Text version of the resource sanitized, if applicable>",
		status: "<HTTP status number>",
		statusText: "<HTTP status text>"
	}
}

Events

Event Trigger What it does
wb-init.wb-data-json Triggered manually (e.g., $( "[data-json-after], [data-json-append], [data-json-before], [data-json-prepend], [data-json-replace], [data-json-replacewith]" ).trigger( "wb-init.wb-data-json" );). Used to manually initialize the Data JSON plugin. Note: The Data JSON plugin will be initialized automatically unless the required markup is added after the page has already loaded.
wb-ready.wb-data-json Triggered automatically after the content has been inserted. Used to identify where content has been inserted in by the plugin (target of the event) and to pass along how the content was included ("after", "append", "before", "prepend", "replace" or "replacewith").
$( document ).on( "wb-ready.wb-data-json", "[data-json-after], [data-json-append], [data-json-before], [data-json-prepend], [data-json-replace], [data-json-replacewith]", function( event, ajaxType ) {
	});
$( "[data-json-after], [data-json-append], [data-json-before], [data-json-prepend], [data-json-replace], [data-json-replacewith]" ).on( "wb-ready.wb-data-json", function( event, ajaxType ) {
	});
wb-ready.wb Triggered automatically when WET has finished loading and executing. Used to identify when all WET plugins and polyfills have finished loading and executing.
$( document ).on( "wb-ready.wb", function( event ) {
	});
wb-contentupdated Triggered automatically when data-json has finished to load the response. Use to perform a secondary action upon inserted content
$('#mycontainer').on( "wb-contentupdated", function( event, data ){
	});

Source code

Data JSON plugin source code on GitHub

Date de modification :