JSON Editor
JSON Editor 根據定義的JSON Schema 生成了一個Html 表單來對JSON進行編輯。它完整支持JSON Schema 的版本3和版本4,並且它集成了一些流行的CSS 框架,例如bootstrap, foundation, and jQueryUI等。
JSON Editor 生成的編輯器支持輸入框、下拉框、等幾乎所有的html5輸入元素
點擊這里查看官網在線示例: http://jeremydorn.com/json-editor/
點擊下面鏈接進行下載
依賴項
JSON Editor 不需要任何的依賴,僅僅需要一個現代瀏覽器支持即可。已在chrome 和firefox 測試通過。
可選的選項
下列內容不需要,但是如果配置的話,可以提升Json Editor 樣式和可用性
- 可兼容的JS模版年引擎 (例如 Mustache, Underscore, Hogan, Handlebars, Swig, Markup, or EJS)
- 一個兼容的CSS框架 (例如bootstrap 2/3, foundation 3/4/5, or jqueryui)
- 一個兼容的圖標庫(例如bootstrap 2/3 glyphicons, foundation icons 2/3, jqueryui, or font awesome 3/4)
- SCEditor 一個所見即所得的html編輯工具
- EpicEditor 一個支持Markdown的編輯器
- Ace Editor 代碼編輯器
- Select2 一個好看的下拉框組件
使用方法
如果你學習Json Editor的用法,可以參看下面的例子
- 基礎用法 - http://rawgithub.com/jdorn/json-editor/master/examples/basic.html
- 高級用法 - http://rawgithub.com/jdorn/json-editor/master/examples/advanced.html
- 集成CSS框架的用法 - http://rawgithub.com/jdorn/json-editor/master/examples/css_integration.html
本文檔包含了JSON Editor的詳細的用法,如果你想獲取更多的有用信息,請訪問wiki
初始化
var element = document.getElementById('editor_holder');
var editor = new JSONEditor(element, options);
選項
Options 可以在全局統一設置,也可以在每個實例初始話的時候單獨設置
// 全局統一設置
JSONEditor.defaults.options.theme = 'bootstrap2';
// 實例初始化的時候設置
var editor = new JSONEditor(element, {
//...
theme: 'bootstrap2'
});
下面是Json Editor 可用的一些選框
選項 | 描述 | 默認值 |
---|---|---|
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
事件
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"
}
});
監聽Change事件
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();
集成CSS
JSON Editor 可以集成一些比較流行的CSS框架
目前支持以下框架:
- html (the default)
- bootstrap2
- bootstrap3
- foundation3
- foundation4
- foundation5
- jqueryui
默認皮膚是 html
, 使用這個選項的時候,沒有任何的class 和樣式.
通過修改變量 JSONEditor.defaults.options.theme
的值,可以改變默認的CSS 框架
JSONEditor.defaults.options.theme = 'foundation5';
你也可以在實例化的時候覆蓋默認值,通過如下方式
var editor = new JSONEditor(element,{
schema: schema,
theme: 'jqueryui'
});
圖標庫
JSON Editor 支持流行的圖標庫.
目前支持以下圖標庫:
- bootstrap2 (glyphicons)
- bootstrap3 (glyphicons)
- foundation2
- foundation3
- jqueryui
- fontawesome3
- fontawesome4
默認情況下沒有使用圖標庫,和設置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 Schema Support
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.
$ref and definitions
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.
hyper-schema links
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:
- prop4 (order 1)
- prop2 (order 10)
- prop1 (order 1000)
- prop3 (order 1001)
默認屬性
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:
- color
- date
- datetime
- datetime-local
- month
- number
- range
- tel
- text
- textarea
- time
- url
- week
下面是一個用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:
- actionscript
- batchfile
- c
- c++
- cpp (alias for c++)
- coffee
- csharp
- css
- dart
- django
- ejs
- erlang
- golang
- handlebars
- haskell
- haxe
- html
- ini
- jade
- java
- javascript
- json
- less
- lisp
- lua
- makefile
- markdown
- matlab
- mysql
- objectivec
- pascal
- perl
- pgsql
- php
- python
- r
- ruby
- sass
- scala
- scss
- smarty
- sql
- stylus
- svg
- twig
- vbscript
- xml
- yaml
{
"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}}
這樣的模板。你可以通過配置來是編輯器支持其他的一些比較流行的模版引擎。
目前支持的模板引擎有
- ejs
- handlebars
- hogan
- markup
- mustache
- swig
- underscore
你可以通過修改默認的配置項 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" }
}
}
}
Custom Template Engines
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
});
Language and String Customization
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";
Custom Editor Interfaces
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"
}
}
}
}
如果你創建了一個對其他人有用的自定義的編輯器,請提交並分享它給別人!
可能性是無窮無盡的。下面有一些好的些想法:
- 用一個緊湊的方式去編輯
- 下拉框用單選按鈕來實現
- 字符串的自動提示,類似枚舉但是並不局限於枚舉
- 字符串數組使用tag 方式來實現會更好些
- 基於Canvas的圖片編輯器等
自定義驗證
// 如果驗證通過返回一個空的數組,驗證不通過則需要返回錯誤信息
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 加載到頁面的時候,你可以用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);
});