JSON Editor 根据定义的JSON Schema 生成了一个Html 表单来对JSON进行编辑。它完整支持JSON Schema 的版本3和版本4,而且它集成了一些流行的CSS 框架,例如bootstrap, foundation, and jQueryUI等。
JSON Editor 生成的编辑器支持输入框、下拉框、等几乎全部的html5输入元素javascript
点击这里查看官网在线示例: http://jeremydorn.com/json-editor/php
点击下面连接进行下载css
JSON Editor 不须要任何的依赖,仅仅须要一个现代浏览器支持便可。已在chrome 和firefox 测试经过。html
下列内容不须要,可是若是配置的话,能够提高Json Editor 样式和可用性html5
若是你学习Json Editor的用法,能够参看下面的例子java
本文档包含了JSON Editor的详细的用法,若是你想获取更多的有用信息,请访问wikinode
var element = document.getElementById('editor_holder'); var editor = new JSONEditor(element, options);
Options 能够在全局统一设置,也能够在每一个实例初始话的时候单独设置python
// 全局统一设置 JSONEditor.defaults.options.theme = 'bootstrap2'; // 实例初始化的时候设置 var editor = new JSONEditor(element, { //... theme: 'bootstrap2' });
下面是Json Editor 可用的一些选框mysql
选项 | 描述 | 默认值 |
---|---|---|
ajax | 若是设置为 true , JSON Editor 将会用$ref 扩展的URL去加载一个ajax请求. |
false |
disable_array_add | 若是设置 true , 数组对象将不显示增长按钮. |
false |
disable_array_delete | 若是设置为 true , 数组对象将不显示删除按钮. |
false |
disable_array_reorder | 若是设置为 true , 数组对象将不显示“向上”、“向下”移动按钮. |
false |
disable_collapse | 若是设置为 true , 对象和数组再也不显示“折叠”按钮. |
false |
disable_edit_json | 若是设置为 true , 将隐藏 Edit JSON 按钮. |
false |
disable_properties | 若是设置为 true , 将隐藏编辑属性按钮. |
false |
form_name_root | 编辑器中输入框的name属性的开头部分,例如一个一个输入框的name 是 `root[person][name]` 其中 "root" 就是这个值. | root |
iconlib | 编辑器使用的图标库. 能够在 CSS Integration 节点查看更多信息. | null |
no_additional_properties | 若是设置为 true , 对象将只能包含被定义在 properties 中属性,设置为false 时,当有一个额外的不在properties 的属性时,这个属性为自动附加到对象中去. |
false |
refs | 包含Schema定义对象的一个URL. 它容许你事先定义好一个JSON Schema供其余地方调用. | {} |
required_by_default | If true , all schemas that don't explicitly set the required property will be required. |
false |
keep_oneof_values | 若是设置为 true ,当切换下拉框的时候它能够将oneOf 中的属性拷贝到对象中去. |
true |
schema | 编辑器锁须要的JSON Schema . 目前支持 版本 3 和版本 4 | {} |
show_errors | 是否显示错误信息,可用的值有interaction , change , always , and never . |
"interaction" |
startval | Seed the editor with an initial value. This should be valid against the editor's schema. | null |
template | 要使用的js 模板引擎. 在此节模板和变量有更多信息 . | default |
theme | CSS 框架名. | html |
__*Note__ 若是 ajax
属性被设置为 true
而且 JSON Editor 须要从扩展URL中获取数据, API中的一些方法不会立刻被生效
请在调用代码前监听 ready
事件jquery
editor.on('ready',function() { // Now the api methods will be available editor.validate(); });
editor.setValue({name: "John Smith"}); var value = editor.getValue(); console.log(value.name) // Will log "John Smith"
Instead of getting/setting the value of the entire editor, you can also work on individual parts of the schema:
// Get a reference to a node within the editor var name = editor.getEditor('root.name'); // `getEditor` will return null if the path is invalid if(name) { name.setValue("John Smith"); console.log(name.getValue()); }
When feasible, JSON Editor won't let users enter invalid data. This is done by
using input masks and intelligently enabling/disabling controls.
However, in some cases it is still possible to enter data that doesn't validate against the schema.
You can use the validate
method to check if the data is valid or not.
// Validate the editor's current value against the schema var errors = editor.validate(); if(errors.length) { // errors is an array of objects, each with a `path`, `property`, and `message` parameter // `property` is the schema keyword that triggered the validation error (e.g. "minLength") // `path` is a dot separated path into the JSON object (e.g. "root.path.to.field") console.log(errors); } else { // It's valid! }
By default, this will do the validation with the editor's current value.
If you want to use a different value, you can pass it in as a parameter.
// Validate an arbitrary value against the editor's schema var errors = editor.validate({ value: { to: "test" } });
The change
event is fired whenever the editor's value changes.
editor.on('change',function() { // Do something }); editor.off('change',function_reference);
You can also watch a specific field for changes:
editor.watch('path.to.field',function() { // Do something }); editor.unwatch('path.to.field',function_reference);
This lets you disable editing for the entire form or part of the form.
// Disable entire form editor.disable(); // Disable part of the form editor.getEditor('root.location').disable(); // Enable entire form editor.enable(); // Enable part of the form editor.getEditor('root.location').enable(); // Check if form is currently enabled if(editor.isEnabled()) alert("It's editable!");
This removes the editor HTML from the DOM and frees up resources.
editor.destroy();
JSON Editor 能够集成一些比较流行的CSS框架
目前支持如下框架:
默认皮肤是 html
, 使用这个选项的时候,没有任何的class 和样式.
经过修改变量 JSONEditor.defaults.options.theme
的值,能够改变默认的CSS 框架
JSONEditor.defaults.options.theme = 'foundation5';
你也能够在实例化的时候覆盖默认值,经过以下方式
var editor = new JSONEditor(element,{ schema: schema, theme: 'jqueryui' });
JSON Editor 支持流行的图标库.
目前支持如下图标库:
默认状况下没有使用图标库,和设置CSS 皮肤同样,你能够全局设置或实例化的时候设置
// Set the global default JSONEditor.defaults.options.iconlib = "bootstrap2"; // Set the icon lib during initialization var editor = new JSONEditor(element,{ schema: schema, iconlib: "fontawesome4" });
你也能够建立你本身的自定义的皮肤或图标库,你能够参考一些示例。
JSON Editor fully supports version 3 and 4 of the JSON Schema core and validation specifications.
Some of The hyper-schema specification is supported as well.
JSON Editor supports schema references to external URLs and local definitions. Here's an example showing both:
{ "type": "object", "properties": { "name": { "title": "Full Name", "$ref": "#/definitions/name" }, "location": { "$ref": "http://mydomain.com/geo.json" } }, "definitions": { "name": { "type": "string", "minLength": 5 } } }
Local references must point to the definitions
object of the root node of the schema.
So, #/customkey/name
will throw an exception.
If loading an external url via Ajax, the url must either be on the same domain or return the correct HTTP cross domain headers.
If your URLs don't meet this requirement, you can pass in the references to JSON Editor during initialization (see Usage section above).
Self-referential $refs are supported. Check out examples/recursive.html
for usage examples.
The links
keyword from the hyper-schema specification can be used to add links to related documents.
JSON Editor will use the mediaType
property of the links to determine how best to display them.
Image, audio, and video links will display the media inline as well as providing a text link.
Here are a couple examples:
Simple text link
{ "title": "Blog Post Id", "type": "integer", "links": [ { "rel": "comments", "href": "/posts/{{self}}/comments/" } ] }
Show a video preview (using HTML5 video)
{ "title": "Video filename", "type": "string", "links": [ { "href": "/videos/{{self}}.mp4", "mediaType": "video/mp4" } ] }
The href
property is a template that gets re-evaluated every time the value changes.
The variable self
is always available. Look at the Dependencies section below for how to include other fields or use a custom template engine.
There is no way to specify property ordering in JSON Schema (although this may change in v5 of the spec).
JSON Editor introduces a new keyword propertyOrder
for this purpose. The default property order if unspecified is 1000. Properties with the same order will use normal JSON key ordering.
{ "type": "object", "properties": { "prop1": { "type": "string" }, "prop2": { "type": "string", "propertyOrder": 10 }, "prop3": { "type": "string", "propertyOrder": 1001 }, "prop4": { "type": "string", "propertyOrder": 1 } } }
In the above example schema, prop1
does not have an order specified, so it will default to 1000.
So, the final order of properties in the form (and in returned JSON data) will be:
The default behavior of JSON Editor is to include all object properties defined with the properties
keyword.
To override this behaviour, you can use the keyword defaultProperties
to set which ones are included:
{ "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"} }, "defaultProperties": ["name"] }
Now, only the name
property above will be included by default. You can use the "Object Properties" button
to add the "age" property back in.
JSON Editor supports many different formats for schemas of type string
. They will work with schemas of type integer
and number
as well, but some formats may produce weird results.
If the enum
property is specified, format
will be ignored.
JSON Editor uses HTML5 input types, so some of these may render as basic text input in older browsers:
下面是一个用format格式化生成一个选择颜色控件的例子
{ "type": "object", "properties": { "color": { "type": "string", "format": "color" } } }
In addition to the standard HTML input formats, JSON Editor can also integrate with several 3rd party specialized editors. These libraries are not included in JSON Editor and you must load them on the page yourself.
SCEditor provides WYSIWYG editing of HTML and BBCode. To use it, set the format to html
or bbcode
and set the wysiwyg
option to true
:
{ "type": "string", "format": "html", "options": { "wysiwyg": true } }
You can configure SCEditor by setting configuration options in JSONEditor.plugins.sceditor
. Here's an example:
JSONEditor.plugins.sceditor.emoticonsEnabled = false;
EpicEditor is a simple Markdown editor with live preview. To use it, set the format to markdown
:
{ "type": "string", "format": "markdown" }
You can configure EpicEditor by setting configuration options in JSONEditor.plugins.epiceditor
. Here's an example:
JSONEditor.plugins.epiceditor.basePath = 'epiceditor';
Ace Editor is a syntax highlighting source code editor. You can use it by setting the format to any of the following:
{ "type": "string", "format": "yaml" }
You can use the hyper-schema keyword media
instead of format
too if you prefer for formats with a mime type:
{ "type": "string", "media": { "type": "text/html" } }
You can override the default Ace theme by setting the JSONEditor.plugins.ace.theme
variable.
JSONEditor.plugins.ace.theme = 'twilight';
默认的布尔类型编辑器是一个包含true,false的下拉框,若是设置format=checkbox
那么将以勾选框的形式展现
{ "type": "boolean", "format": "checkbox" }
默认的数组编辑器会占用比较大的屏幕空间. 使用 table
and tabs
格式选项能够能够将界面变得紧凑些
table
选项在数组的结构相同而且不复杂的时候用起来会比较好
tabs
选项能够针对任何数组, 可是每次只能显示数组中的一项. 在每一个数组项的左边会有一个页签开关.
下面是一个 table
选项的例子:
{ "type": "array", "format": "table", "items": { "type": "object", "properties": { "name": { "type": "string" } } } }
对于数组中的枚举字符串,你可使用select
or checkbox
选项,这两个选项须要一个相似以下的特殊结构才能工做
{ "type": "array", "uniqueItems": true, "items": { "type": "string", "enum": ["value1","value2"] } }
默认状况下(不设置format的状况),若是枚举的选项少于8个的时候,将会启用checkbox
编辑器,不然的话会启用select 编辑器
你能够经过下面的代码的方式来覆盖默认项
{ "type": "array", "format": "select", "uniqueItems": true, "items": { "type": "string", "enum": ["value1","value2"] } }
默认状况下对象每一个子对象会布局一行,format=grid
的时候,每行能够放多个子对象编辑器
This can make the editor much more compact, but at a cost of not guaranteeing child editor order.
{ "type": "object", "properties": { "name": { "type": "string" } }, "format": "grid" }
Editors can accept options which alter the behavior in some way.
collapsed
- 折叠disable_array_add
- 禁用增长按钮disable_array_delete
- 禁用删除按钮disable_array_reorder
- 禁用移动on个按钮disable_collapse
- 禁用折叠disable_edit_json
- 禁用JSON编辑按钮disable_properties
- 禁用属性按钮enum_titles
- 枚举标题,对应 enum
属性。当使用select 的时候,将显示enum_titles的内容,可是值仍是来自enumexpand_height
- If set to true, the input will auto expand/contract to fit the content. Works best with textareas.grid_columns
- Explicitly set the number of grid columns (1-12) for the editor if it's within an object using a grid layout.hidden
- 编辑器是否隐藏input_height
- 编辑器的高度input_width
- 编辑器的宽度remove_empty_properties
- 移除空的对象属性{ "type": "object", "options": { "collapsed": true }, "properties": { "name": { "type": "string" } } }
You can globally set the default options too if you want:
JSONEditor.defaults.editors.object.options.collapsed = true;
有的时候,一个字段的值依赖于另一个字段,这是不可避免年遇到的问题
JSON Schema中 dependencies
选项 不能足够灵活的处理一些实例,所以 JSON Editor 引入了一个复合的自定义关键词来解决这个问题
第一步,修改Schema增长一个watch 属性
{ "type": "object", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" }, "full_name": { "type": "string", "watch": { "fname": "first_name", "lname": "last_name" } } } }
关键词watch
告诉JSON Editor 哪一个字段被更改了
关键词 (fname
and lname
例子中) 是这个属性的别名
两个属性的值 (first_name
and last_name
) 是一个属性的路径.(例如 "path.to.field").
默认路径是来从架构的根开始,可是你能够在架构中年建立一个id属性做为锚点,来建立一个相对路径.这在数组中至关的有用.
下面是一个例子
{ "type": "array", "items": { "type": "object", "id": "arr_item", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" }, "full_name": { "type": "string", "watch": { "fname": "arr_item.first_name", "lname": "arr_item.last_name" } } } } }
那如今 full_name
在每一个数组元素中将被 first_name
and last_name
两个字段监控
监控字段并不能作任何事情。拿上面的例子来讲,你还须要告诉编辑器,full_name
的内容多是相似这样的格式fname [space] lname
编辑器使用了一个js模版引擎去实现它。
默认编辑器包含了一个简单的模板引擎,它仅仅只能替换相似{{variable}}
这样的模板。你能够经过配置来是编辑器支持其余的一些比较流行的模版引擎。
目前支持的模板引擎有
你能够经过修改默认的配置项 JSONEditor.defaults.options.template
来支持模板引擎,以下
JSONEditor.defaults.options.template = 'handlebars';
你也能够在实例初始化的时候来设置
var editor = new JSONEditor(element,{ schema: schema, template: 'hogan' });
这里有一个使用了模板引擎的完整的 full_name
的例子,供参考
{ "type": "object", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" }, "full_name": { "type": "string", "template": "{{fname}} {{lname}}", "watch": { "fname": "first_name", "lname": "last_name" } } } }
另一个常见的状况就是其余的字段的值依赖于下拉菜单的值参考下面的例子
{ "type": "object", "properties": { "possible_colors": { "type": "array", "items": { "type": "string" } }, "primary_color": { "type": "string" } } }
让我来告诉你,你想强制primary_color
为一个possible_colors
数组中的一个。
首先,咱们必须告诉 primary_color
字段监控possible_colors
数组
{ "primary_color": { "type": "string", "watch": { "colors": "possible_colors" } } }
接下来,咱们使用一个特殊的关键词 enumSource
去告诉编辑器,咱们想使用这个字段去填充下拉框
{ "primary_color": { "type": "string", "watch": { "colors": "possible_colors" }, "enumSource": "colors" } }
那么一旦possible_colors
数组的值发生变化,下拉菜单的值将被改变
这是 enumSource
的最基本的用法。
这个属性支持更多的动做,例如 filtering, pulling from multiple sources, constant values 等等。
这里有一个复杂的例子,它使用swig模板引擎的语法去显示高级特性
{ // An array of sources "enumSource": [ // Constant values ["none"], { // A watched field source "source": "colors", // Use a subset of the array "slice": [2,5], // Filter items with a template (if this renders to an empty string, it won't be included) "filter": "{% if item !== 'black' %}1{% endif %}", // Specify the display text for the enum option "title": "{{item|upper}}", // Specify the value property for the enum option "value": "{{item|trim}}" }, // Another constant value at the end of the list ["transparent"] ] }
你也可使用以下语法去实现一个特殊的一个静态列表。
{ "enumSource": [{ // A watched field source "source": [ { "value": 1, "title": "One" }, { "value": 2, "title": "Two" } ], "title": "{{item.title}}", "value": "{{item.value}}" }] ] }
这个例子直接使用了一个字符串数组。使用表单动做,你也能够将它构形成一个对象的数组,例如
{ "type": "object", "properties": { "possible_colors": { "type": "array", "items": { "type": "object", "properties": { "text": { "type": "string" } } } }, "primary_color": { "type": "string", "watch": { "colors": "possible_colors" }, "enumSource": [{ "source": "colors", "value": "{{item.text}}" }] } } }
在这个动做表单中,全部的模板选项都有一个item 和i 属性。
item 指代的是数组元素
i 是一个从0开始的序号
The title
keyword of a schema is used to add user friendly headers to the editing UI. Sometimes though, dynamic headers, which change based on other fields, are helpful.
Consider the example of an array of children. Without dynamic headers, the UI for the array elements would show Child 1
, Child 2
, etc..
It would be much nicer if the headers could be dynamic and incorporate information about the children, such as 1 - John (age 9)
, 2 - Sarah (age 11)
.
To accomplish this, use the headerTemplate
property. All of the watched variables are passed into this template, along with the static title title
(e.g. "Child"), the 0-based index i0
(e.g. "0" and "1"), the 1-based index i1
, and the field's value self
(e.g. {"name": "John", "age": 9}
).
{ "type": "array", "title": "Children", "items": { "type": "object", "title": "Child", "headerTemplate": "{{ i1 }} - {{ self.name }} (age {{ self.age }})", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } } } }
If one of the included template engines isn't sufficient,
you can use any custom template engine with a compile
method. For example:
var myengine = { compile: function(template) { // Compile should return a render function return function(vars) { // A real template engine would render the template here var result = template; return result; } } }; // Set globally JSONEditor.defaults.options.template = myengine; // Set on a per-instance basis var editor = new JSONEditor(element,{ schema: schema, template: myengine });
JSON Editor uses a translate function to generate strings in the UI. A default en
language mapping is provided.
You can easily override individual translations in the default language or create your own language mapping entirely.
// Override a specific translation JSONEditor.defaults.languages.en.error_minLength = "This better be at least {{0}} characters long or else!"; // Create your own language mapping // Any keys not defined here will fall back to the "en" language JSONEditor.defaults.languages.es = { error_notset: "propiedad debe existir" };
By default, all instances of JSON Editor will use the en
language. To override this default, set the JSONEditor.defaults.language
property.
JSONEditor.defaults.language = "es";
JSON Editor contains editor interfaces for each of the primitive JSON types as well as a few other specialized ones.
You can add custom editors interfaces fairly easily. Look at any of the existing ones for an example.
JSON Editor uses resolver functions to determine which editor interface to use for a particular schema or subschema.
Let's say you make a custom location
editor for editing geo data. You can add a resolver function to use this custom editor when appropriate. For example:
// Add a resolver function to the beginning of the resolver list // This will make it run before any other ones JSONEditor.defaults.resolvers.unshift(function(schema) { if(schema.type === "object" && schema.format === "location") { return "location"; } // If no valid editor is returned, the next resolver function will be used });
The following schema will now use this custom editor for each of the array elements instead of the default object
editor.
{ "type": "array", "items": { "type": "object", "format": "location", "properties": { "longitude": { "type": "number" }, "latitude": { "type": "number" } } } }
若是你建立了一个对其余人有用的自定义的编辑器,请提交并分享它给别人!
可能性是无穷无尽的。下面有一些好的些想法:
// 若是验证经过返回一个空的数组,验证不经过则须要返回错误信息 JSONEditor.defaults.custom_validators.push(function(schema, value, path) { var errors = []; if(schema.format==="date") { if(!/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value)) { // Errors must be an object with `path`, `property`, and `message` errors.push({ path: path, property: 'format', message: 'Dates must be in the format "YYYY-MM-DD"' }); } } return errors; });
当jquery 加载到页面的时候,你能够用jquery 的方式去加载插件,以下
$("#editor_holder") .jsoneditor({ schema: {}, theme: 'bootstrap3' }) .on('ready', function() { // Get the value var value = $(this).jsoneditor('value'); value.name = "John Smith"; // Set the value $(this).jsoneditor('value',value); });