Introduction
This article is to share with you an interesting source and/or concept about json schema.
Json is really useful for JavaScript, and like XML with the DTD (http://www.w3schools.com/xml/xml_dtd.asp), json has schema (http://json-schema.org/).
This is really interesting because by the schema (the datatype), you can specify the type of value and then describe the form for this type of value like CRUD for the SQL table.
There is an excellent package in jquery that will help you for that: https://github.com/jdorn/json-editor/.
I want to demonstrate this by a bootstrap menu editor in PHP, and you'll see how much the form could be complicated by a simple declaration of datatype
.
Editing a Menu
At the beginning, you have only a root entry, so to add a menu child, click on Properties, and choose the children, and enter a name.
To preview your work, click on Submit.
Using the Code
The json schema is:
schema: {
title: "Menu",
format: "grid",
$ref: "#/definitions/menu",
definitions: {
menu: {
type: "object",
id: "menu",
headerTemplate: "{{ self.name }}",
defaultProperties: [
"name",
"children"
],
properties: {
name: {
title: "Name",
type: "string"
},
isdivider: {
title: "divider",
type: "string",
"enum": [false,true]
},
children: {
type: "array",
items: {
title: "Children",
$ref: "#/definitions/menu"
}
}
}
}
}
The jquery plugin is called by the line:
var editor = new JSONEditor(document.getElementById('editor_holder'),{
There's an important variable (menu) that contains the json value in object php type.
The schema describes a recursive structure with the possible field (name
, isdivider
, and children
).
The part rendering the menu is the function recursive_menu
.
function recursive_menu( $obj ,$deep)
Points of Interest
There is an interesting point about this json schema, if you want to change technology, then it is possible without changing everything, it is the re-usability.
For example, if you want to go in the Angularjs side, it's possible easily because there is the same thing with Angular js https://github.com/Textalk/angular-schema-form
Then, you can re-use your JSON schema with Angularjs, the same with Python.