JSON Schema

JSON Schema is a JSON-based schema definition language. It defines the expected layout of a JSON document, but does not describe its semantics.

{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"$id": "https://example.com/example.schema.json",
	"description": "Example schema",
	"type": "object",
	"properties": [
		"foo": {
			"description": "Schema of the `foo` property",
			"type": "string"
		}
	]
}

TreeLDR can generate a JSON Schema from a TreeLDR layout. It can also import a TreeLDR layout from a JSON Schema, although it will result in an orphan layout: a layout not associated to any type, and without any semantic information. For instance, the above JSON Schema is equivalent to the following TreeLDR layout:

/// Example schema.
layout Example {
	/// Schema of the `foo` property.
	foo: xs:string
}

Generating a JSON Schema

Generating a JSON-LD context is done by using the json-schema subcommand of the command line utility after the list of inputs, and by specifying what layout should be turned into a JSON Schema.

tldrc -i input1 ... -i inputN json-schema path/to/Layout

For instance, consider the following layout for the schema:BlogPosting type:

// example/basic_post.tldr
base <https://example.com/>;
use <https://schema.org/> as schema;

layout BasicPost for schema:BlogPosting {
	/// Title of the post.
	schema:title: schema:Text,

	/// Content of the post.
	schema:body: schema:Text
}

Use the following command to generate JSON Schema context:

tldrc -i example/basic_post.tldr -i example/schema.org.tldr json-schema https://example.com/BasicPost 

Running that generates:

{
	"$id": "https://example.com/BasicPost",
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"properties": {
		"body": {
			"description": "Content of the post.",
			"type": "string"
		},
		"title": {
			"description": "Title of the post.",
			"type": "string"
		}
	},
	"title": "Basic Blog Post.",
	"type": "object"
}

The resulting schema loses any Linked Data information.

Importing a JSON Schema

The TreeLDR compiler (tldrc) can import a JSON Schema like any other input document using the -i option. This will import the JSON Schema as an orphan TreeLDR layout. For instance, we can import and export back the previously generate JSON Schema above, and we will get back the same document:

tldrc -i examples/basic_post.schema.json json-schema https://example.com/BasicPost

Last updated