@accordion/json-editor 中文文档教程

发布于 3年前 浏览 25 项目主页 更新于 3年前

JSON Editor

构建状态 使用更新的叉 json 编辑器/json 编辑器。 从原始回购中添加了一些拉取请求。

JSON 架构 -> HTML 编辑器 -> JSON<="" p="">

JSON Editor 采用 JSON Schema 并使用它来生成 HTML 表单。 它完全支持 JSON Schema 版本 3 和 4,并且可以与几个流行的 CSS 框架(bootstrap、spectre、tailwind)集成。

查看交互式演示:https://json-editor.github.io/json-editor/

或 JSON-Editor Interactive Playground:https://pmk65.github.io/jedemov2/dist/demo.html

Install

安装包

npm install @json-editor/json-editor

使用a CDN

<script src="https://cdn.jsdelivr.net/npm/@json-editor/json-editor@latest/dist/jsoneditor.min.js"></script>

您还可以使用登录页面从 CDN 访问旧版本:https://www.jsdelivr.com/package/npm/@json-editor/json-editor

对于本地使用,请下载 生产版本开发版

Requirements

JSON 编辑器没有依赖项。 它只需要一个现代浏览器(在 Chrome 和 Firefox 中测试过)。

Optional Requirements

以下内容不是必需的,但可以改进 JSON 编辑器的样式和可用性。

  • A compatible JS template engine (Mustache, Underscore, Hogan, Handlebars, Lodash, Swig, Markup, or EJS)
  • A compatible CSS framework for styling (Spectre, Tailwind, Bootstrap4)
  • A compatible icon library (Spectre, jQueryUI, Font Awesome 3/4/5)
  • SCEditor for WYSIWYG editing of HTML or BBCode content
  • SimpleMDE for editing of Markdown content
  • Ace Editor for editing code
  • Jodit Open Source WYSIWYG editor
  • Autocomplete Accessible autocomplete component
  • Choices for nicer Select & Array boxes
  • Select2 for nicer Select boxes
  • Selectize for nicer Select & Array boxes
  • Flatpickr lightweight and powerful datetime picker
  • Signature Pad HTML5 canvas based smooth signature drawing
  • Vanilla Picker A simple, easy to use vanilla JS color picker with alpha selection
  • Cleave.js for formatting your <input/> content while you are typing
  • IMask.js vanilla javascript input mask
  • math.js for more accurate floating point math (multipleOf, divisibleBy, etc.)
  • DOMPurify DOM-only, super-fast, uber-tolerant XSS sanitizer. (If you want to use HTML format in titles/headers and descriptions.)

Usage

如果您通过示例学习得最好,请查看这些:

  • Basic Usage Example - https://json-editor.github.io/json-editor/basic.html
  • ACE Editor Example - https://json-editor.github.io/json-editor/ace_editor.html
  • Advanced Usage Example - https://json-editor.github.io/json-editor/advanced.html
  • CSS Integration Example - https://json-editor.github.io/json-editor/css_integration.html
  • Base64 Editor Example (Muiltple Upload) - https://json-editor.github.io/json-editor/multipleuploadbase64.html
  • Choices Editor Example - https://json-editor.github.io/json-editor/choices.html
  • Cleave.js Editor Example - https://json-editor.github.io/json-editor/cleave.html
  • Colorpicker Editor Example - https://json-editor.github.io/json-editor/colorpicker.html
  • Datetime Editor Example - https://json-editor.github.io/json-editor/datetime.html
  • DescribedBy Hyperlink Editor Example - https://json-editor.github.io/json-editor/describedby.html
  • iMask.js Editor Example - https://json-editor.github.io/json-editor/imask.html
  • Radio Button JSON Editor Example - https://json-editor.github.io/json-editor/radio.html
  • Recursive JSON Editor Example - https://json-editor.github.io/json-editor/recursive.html
  • Select2 Editor Example - https://json-editor.github.io/json-editor/select2.html
  • Selectize Editor Example - https://json-editor.github.io/json-editor/selectize.html
  • Signature Pad Editor Example - https://json-editor.github.io/json-editor/signature.html
  • Star Rating Editor Example - https://json-editor.github.io/json-editor/starrating.html
  • Upload Editor Example - https://json-editor.github.io/json-editor/upload.html
  • WYSIWYG Editor Example - https://json-editor.github.io/json-editor/wysiwyg.html

可以在 JSON-Editor Interactive Playground

本自述文件的其余部分包含有关 JSON 编辑器各个方面的详细文档。 如需更多底层文档,请查看 wiki。

Initialize

const element = document.getElementById('editor_holder');

const editor = new JSONEditor(element, options);

Options

选项可以全局设置,也可以在实例化期间基于每个实例设置。

// Set an option globally
JSONEditor.defaults.options.theme = 'bootstrap4';

// Set an option during instantiation
const editor = new JSONEditor(element, {
  //...
  theme: 'bootstrap4'
});

以下是所有可用的选项:

Option Description Default Value
ajax If true, JSON Editor will load external URLs in $ref via ajax. false
ajaxBase Allows schema references to work either with or without cors; set to protocol://host:port when api is served by different host.
ajaxCredentials If true, JSON Editor will make ajax call with [credentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials). false
compact If true, the label will not be displayed/added. false
disable_array_add If true, remove all "add row" buttons from arrays. false
disable_array_delete If true, remove all "delete row" buttons from arrays. false
disable_array_delete_all_rows If true, remove all "delete all rows" buttons from arrays. false
disable_array_delete_last_row If true, remove all "delete last row" buttons from arrays. false
disable_array_reorder If true, remove all "move up" and "move down" buttons from arrays. false
enable_array_copy If true, add copy buttons to arrays. false
disable_collapse If true, remove all collapse buttons from objects and arrays. false
disable_edit_json If true, remove all Edit JSON buttons from objects. false
disable_properties If true, remove all Edit Properties buttons from objects. false
array_controls_top If true, array controls (add, delete etc) will be displayed at top of list. false
form_name_root The first part of the `name` attribute of form inputs in the editor. An full example name is `root[person][name]` where "root" is the form_name_root. root
iconlib The icon library to use for the editor. See the CSS Integration section below for more info. null
remove_button_labels Display only icons in buttons. This works only if iconlib is set. false
no_additional_properties If true, objects can only contain properties defined with the properties keyword. false
refs An object containing schema definitions for URLs. Allows you to pre-define external schemas. {}
required_by_default If true, all schemas that don't explicitly set the required property will be required. false
keep_oneof_values If true, makes oneOf copy properties over when switching. true
schema A valid JSON Schema to use for the editor. Version 3 and Version 4 of the draft specification are supported. {}
show_errors When to show validation errors in the UI. Valid values are 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 The JS template engine to use. See the Templates and Variables section below for more info. default
theme The CSS theme to use. See the CSS Integration section below for more info. html
display_required_only If true, only required properties will be included by default. false
show_opt_in If true, NON required properties will have an extra toggable checkbox near the title that determines if the value must be included or not in the editor´s value false
prompt_before_delete If true, displays a dialog box with a confirmation message before node deletion. true
object_layout The default value of `format` for objects. If set to table for example, objects will use table layout if `format` is not specified. normal
enum_source_value_auto_select Preserve value at Move Up or Down.(No value is selected automatically upon deletion.) true
max_depth Max depth of the nested properties to be rendered of provided json schema. The missing of this option could cause "maximum call stack size exceeded" in case of object properties with circular references. 0 value means "render all". 0
use_default_values If true default values based on the "type" of the property will be used true

*注意 如果 ajax 属性为 true 并且 JSON Editor 需要获取外部 url,则 api 方法获胜立即可用。 在调用它们之前监听 ready 事件。

editor.on('ready',() => {
  // Now the api methods will be available
  editor.validate();
});

Get/Set Value

editor.setValue({name: "John Smith"});

const value = editor.getValue();
console.log(value.name) // Will log "John Smith"

除了获取/设置整个编辑器的值,您还可以处理模式的各个部分:

// Get a reference to a node within the editor
const name = editor.getEditor('root.name');

// `getEditor` will return null if the path is invalid
if (name) {
  name.setValue("John Smith");

  console.log(name.getValue());
}

Validate

在可行的情况下,JSON 编辑器不会让用户输入无效数据。 这是由 使用输入掩码和智能启用/禁用控件。

但是,在某些情况下,仍然可以输入未根据架构进行验证的数据。

您可以使用 validate 方法来检查数据是否有效。

// Validate the editor's current value against the schema
const 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!
}

默认情况下,这将使用编辑器的当前值进行验证。 如果要使用不同的值,可以将其作为参数传入。

// Validate an arbitrary value against the editor's schema
const errors = editor.validate({
  value: {
    to: "test"
  }
});

Listen for Changes

只要编辑器的值发生变化,就会触发 change 事件。

editor.on('change',() => {
  // Do something
});

editor.off('change',function_reference);

您还可以监视特定字段的更改:

editor.watch('path.to.field',() => {
  // Do something
});

editor.unwatch('path.to.field',function_reference);

或监视所有字段(类似于“onchange”事件,但跟踪更改的字段)

const watcherCallback = function (path) {
  console.log(`field with path: [${path}] changed to [${JSON.stringify(this.getEditor(path).getValue())}]`);
  // Do something
}
for (let key in editor.editors) {
  if (editor.editors.hasOwnProperty(key) && key !== 'root') {
    editor.watch(key, watcherCallback.bind(editor, key));
  }
}

Enable and Disable the Editor

这使您可以禁用对整个表单或部分表单的编辑。

// 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!");

// Activate part of the form
editor.activate();

// Deactivate part of the form
editor.deactivate();

Destroy

这将从 DOM 中删除编辑器 HTML 并释放资源。

editor.destroy();

CSS Integration

JSON Editor 可以开箱即用地与几个流行的 CSS 框架集成。

当前支持的主题是:

  • barebones
  • html (the default)
  • bootstrap4
  • spectre
  • tailwind

注意:以下主题尚未更新为 2.x 格式,除非有人愿意更新它们,否则将在最终版本中删除。 旧的 1.x 主题在表单输出的底部显示消息 “这是一个旧的 JSON-Editor 1.x 主题,与 2.x 版本一起使用时可能无法正确显示元素”

  • bootstrap2
  • bootstrap3
  • foundation3
  • foundation4
  • foundation5
  • foundation6
  • jqueryui
  • materialize

默认主题为html,不依赖外部框架。 这个默认值可以通过设置 JSONEditor.defaults.options.theme 变量来改变。

如果您想使用 CSS 指定自己的样式,可以使用 barebones,它几乎不包含任何类或内联样式。

JSONEditor.defaults.options.theme = 'spectre';

您可以通过在初始化时传递 theme 参数来基于每个实例覆盖此默认值:

const editor = new JSONEditor(element,{
  schema: schema,
  theme: 'tailwind'
});

Icon Libraries

JSON Editor 还支持几个流行的图标库。 图标库必须独立于主题设置,即使有一些重叠。

支持的图标库是:

  • jqueryui
  • fontawesome3
  • fontawesome4
  • fontawesome5
  • spectre

默认情况下,不使用任何图标。 就像 CSS 主题一样,您可以在全局或初始化时设置图标库:

// Set the global default
JSONEditor.defaults.options.iconlib = "spectre";

// Set the icon lib during initialization
const editor = new JSONEditor(element,{
  schema: schema,
  iconlib: "fontawesome4"
});

也可以创建您自己的自定义主题和/或图标库。 查看任何现有的类以获取示例。

JSON Schema Support

JSON 编辑器完全支持 JSON Schema 核心验证规范。 一些 hyper-schema 规范也受支持。

$ref and definitions

JSON 编辑器支持对外部 URL 和本地定义的模式引用。 这是一个显示两者的示例:

{
  "type": "object",
  "properties": {
    "name": {
      "title": "Full Name",
      "$ref": "#/definitions/name"
    },
    "location": {
      "$ref": "http://mydomain.com/geo.json"
    }
  },
  "definitions": {
    "name": {
      "type": "string",
      "minLength": 5
    }
  }
}

本地引用必须指向模式根节点的 definitions 对象。 所以,#/customkey/name 会抛出异常。

如果通过 Ajax 加载外部 url,则 url 必须在同一域中或返回正确的 HTTP 跨域标头。 如果您的 URL 不满足此要求,您可以在初始化期间将引用传递给 JSON 编辑器(请参阅上面的使用部分)。

支持自引用 $refs。 查看 examples/recursive.html 以获取使用示例。

超模式规范中的 links 关键字可用于添加指向相关文档的链接。

JSON 编辑器将使用链接的 mediaType 属性来确定如何最好地显示它们。 图像、音频和视频链接将内联显示媒体并提供文本链接。

下面是几个示例:

简单的文本链接

{
  "title": "Blog Post Id",
  "type": "integer",
  "links": [
    {
      "rel": "comments",
      "href": "/posts/{{self}}/comments/",
      // Optional - set CSS classes for the link
      "class": "comment-link open-in-modal primary-text"
    }
  ]
}

单击时进行链接下载

{
  "title": "Document filename",
  "type": "string",
  "links": [
    {
      "rel": "Download File",
      "href": "/documents/{{self}}",
      // Can also set `download` to a string as per the HTML5 spec
      "download": true
    }
  ]
}

显示视频预览(使用 HTML5 视频)

{
  "title": "Video filename",
  "type": "string",
  "links": [
    {
      "href": "/videos/{{self}}.mp4",
      "mediaType": "video/mp4"
    }
  ]
}

href 属性是一个模板,每次值更改时都会重新评估。 变量 self 始终可用。 查看下面的依赖项部分,了解如何包含其他字段或使用自定义模板引擎。

Property Ordering

无法在 JSON Schema 中指定属性顺序(尽管这可能会在规范的 v5 中更改)。

为此,JSON 编辑器引入了一个新关键字 propertyOrder。 如果未指定,则默认属性顺序为 1000。具有相同顺序的属性将使用正常的 JSON 键顺序。

{
  "type": "object",
  "properties": {
    "prop1": {
      "type": "string"
    },
    "prop2": {
      "type": "string",
      "propertyOrder": 10
    },
    "prop3": {
      "type": "string",
      "propertyOrder": 1001
    },
    "prop4": {
      "type": "string",
      "propertyOrder": 1
    }
  }
}

在上面的示例架构中,prop1 没有指定顺序,因此默认为 1000。 因此,表单(以及返回的 JSON 数据)中属性的最终顺序将是:

  1. prop4 (order 1)
  2. prop2 (order 10)
  3. prop1 (order 1000)
  4. prop3 (order 1001)

Default Properties

JSON 编辑器的默认行为是包括使用 properties 关键字定义的所有对象属性。

要覆盖此行为,您可以使用关键字 defaultProperties 来设置包含哪些属性:

{
  "type": "object",
  "properties": {
    "name": {"type": "string"},
    "age": {"type": "integer"}
  },
  "defaultProperties": ["name"]
}

现在,默认情况下只会包含上面的 name 属性。 您可以使用“对象属性”按钮 添加“age”属性

format

。JSON 编辑器支持许多不同格式的 string 类型的模式。 它们也可以使用 integernumber 类型的模式,但某些格式可能会产生奇怪的结果。 如果指定了 enum 属性,则 format 将被忽略。

JSON 编辑器使用 HTML5 输入类型,因此其中一些可能会在旧版浏览器中呈现为基本文本输入:

  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • password
  • number
  • range
  • tel
  • text
  • textarea
  • time
  • url
  • week

这是一个示例,将在支持它的浏览器中显示颜色选择器:

{
  "type": "object",
  "properties": {
    "color": {
      "type": "string",
      "format": "color"
    }
  }
}

String Editors Input Attributes

您可以设置自定义属性,例如 placeholderclassdata- 使用特殊选项关键字 inputAttributes 在输入字段上。

像这样:

{
  "type": "object",
  "properties": {
    "name": {
      "title": "Full Name",
      "options": {
        "inputAttributes": {
          "placeholder":  "your name here...",
          "class": "myclass"
        }
      }
    }
  }
}

Specialized String Editors

除了标准的 HTML 输入格式外,JSON Editor 还可以与多个 3rd 方专业编辑器集成。 这些库不包含在 JSON 编辑器中,您必须自己将它们加载到页面上。

SCEditor 提供所见即所得的 HTML 和 BBCode 编辑。 要使用它,请将格式设置为 htmlbbcode 并将 wysiwyg 选项设置为 true

{
  "type": "string",
  "format": "html",
  "options": {
    "wysiwyg": true
  }
}

SimpleMDE 是一个带有实时预览功能的简单 Markdown 编辑器。 要使用它,请将格式设置为 markdown

{
  "type": "string",
  "format": "markdown"
}

Ace Editor 是一个语法高亮源代码编辑器。 您可以通过将格式设置为以下任何一种来使用它:

  • actionscript
  • batchfile
  • c
  • c++
  • cpp (alias for c++)
  • coffee
  • csharp
  • css
  • dart
  • django
  • ejs
  • erlang
  • golang
  • groovy
  • 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"
}

如果您更喜欢 mime 类型的格式,也可以使用超架构关键字 media 而不是 format

{
  "type": "string",
  "media": {
    "type": "text/html"
  }
}

您可以通过在 options.ace模式。

{
  "type": "string",
  "format": "sql",
  "options": {
    "ace": {
      "theme": "ace/theme/vibrant_ink",
      "tabSize": 2,
      "useSoftTabs": true,
      "wrap": true
    }
  }
}

Booleans

默认的布尔编辑器是一个带有选项“true”和“false”的选择框。 要改用复选框,请将格式设置为 checkbox

{
  "type": "boolean",
  "format": "checkbox"
}

Arrays

默认的数组编辑器占用了大量的屏幕空间。 tabletabs 格式为编辑数组提供了更紧凑的 UI。

当每个数组元素都具有相同的模式并且不太复杂时,table 格式非常有用。

tabs 格式可以处理任何数组,但一次只能显示一个数组元素。 它的左侧有用于在项目之间切换的选项卡。

tabs-top 格式将选项卡放在顶部。

以下是 table 格式的示例:

{
  "type": "array",
  "format": "table",
  "items": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string"
      }
    }
  }
}

对于枚举字符串数组,您还可以使用 selectcheckbox 格式。 这些格式需要非常特定的模式才能工作:

{
  "type": "array",
  "uniqueItems": true,
  "items": {
    "type": "string",
    "enum": ["value1","value2"]
  }
}

默认情况下,如果枚举选项少于 8 个,将使用 checkbox 编辑器(多个复选框)。 否则,将使用 select 编辑器(多选框)。

您可以通过传入格式来覆盖此默认值:

{
  "type": "array",
  "format": "select",
  "uniqueItems": true,
  "items": {
    "type": "string",
    "enum": ["value1","value2"]
  }
}

Array events

添加、删除、上移、移动或删除数组项时,json 编辑器将触发相关事件。

editor.on('moveRow', editor => {
  console.log('moveRow', editor)
});
editor.on('addRow', editor => {
  console.log('addRow', editor)
});
editor.on('deleteRow', editor => {
  console.log('deleteRow', editor)
});
editor.on('deleteAllRows', editor => {
  console.log('deleteAllRows', editor)
});

Objects

默认对象布局是每行一个子编辑器。 grid 格式将改为每行放置多个子编辑器。 这可以使编辑器更加紧凑,但代价是不能保证子编辑器的顺序。 这种格式会拉伸 列来填补空白,直到所有 12 列都被填满。

{
  "type": "object",
  "properties": {
    "name": { "type": "string" }
  },
  "format": "grid"
}

grid-strict 格式将遵循列大小(无拉伸)和属性顺序。 它引入了新的 grid-break 属性来打断当前行,留下 4 列的间隙。

{
  "type": "object",
  "format": "grid-strict",
  "properties": {
    "a": {
      "title": "a",
      "type": "string",
      "options": {
        "grid_columns": 4
      }
    },
    "b": {
      "title": "b",
      "type": "string",
      "options": {
        "grid_columns": 4,
        "grid_break": true
      }
    },
    "c": {
      "title": "c",
      "type": "string",
      "options": {
        "grid_columns": 6
      }
    },
    "d": {
      "title": "d",
      "type": "string",
      "options": {
        "grid_columns": 6
      }
    }
  }
}

categories 格式在顶部选项卡面板中对属性进行分组,一个用于每个对象或数组属性,另外一个用于对所有添加的或其他类型的属性进行分组。 面板选项卡标题来自对象或数组标题,对于分组面板,它默认为“基本”,除非定义了 basicCategoryTitle

{
  "type": "object",
  "properties": {
    "name": { "type": "string" }
  },
  "format": "categories",
  "basicCategoryTitle": "Main"
}

演示页面将如下所示:

Categories format

Editor Options

编辑器可以接受以某种方式改变行为的选项。

  • collapsed - If set to true, the editor will start collapsed (works for objects and arrays)
  • disable_array_add - If set to true, the "add row" button will be hidden (works for arrays)
  • disable_array_delete - If set to true, all of the "delete" buttons will be hidden (works for arrays)
  • disable_array_delete_all_rows - If set to true, just the "delete all rows" button will be hidden (works for arrays)
  • disable_array_delete_last_row - If set to true, just the "delete last row" buttons will be hidden (works for arrays)
  • disable_array_reorder - If set to true, the "move up/down" buttons will be hidden (works for arrays)
  • disable_collapse - If set to true, the collapse button will be hidden (works for objects and arrays)
  • disable_edit_json - If set to true, the Edit JSON button will be hidden (works for objects)
  • disable_properties - If set to true, the Edit Properties button will be hidden (works for objects)
  • array_controls_top - If set to true, array controls (add, delete etc) will be displayed at top of list (works for arrays)
  • enum_titles - An array of display values to use for select box options in the same order as defined with the enum keyword. Works with schema using enum values.
  • expand_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 - If set to true, the editor will not appear in the UI (works for all types)
  • input_height - Explicitly set the height of the input element. Should be a valid CSS width string (e.g. "100px"). Works best with textareas.
  • input_width - Explicitly set the width of the input element. Should be a valid CSS width string (e.g. "100px"). Works for string, number, and integer data types.
  • remove_empty_properties - If set to true for an object, empty object properties (i.e. those with falsy values) will not be returned by getValue().
{
  "type": "object",
  "options": {
    "collapsed": true
  },
  "properties": {
    "name": {
      "type": "string"
    }
  }
}

如果需要,您也可以全局设置默认选项:

JSONEditor.defaults.editors.object.options.collapsed = true;

InfoText

使用选项 infoText,将创建​​一个信息按钮,在悬停时显示您设置的文本。

{
  "type": "string",
  "title": "Name",
  "options": {
    "infoText": "Your full name"
  }
}

Dependencies

有时,有必要让一个字段的值依赖于另一个字段的值。

依赖信息是从控件的选项字段中的依赖字段中获取的。 dependencies 字段应该是一个映射,其中键是所依赖字段的名称,值是预期值。 该值可以是一个数组,以指示多个值的可能性。 这使用内部字段值监视系统来通知字段其依赖项的更改。

这是一个示例模式:

{
  "title": "An object",
  "type": "object",
  "properties": {
    "fieldOne": {
      "title": "I should be changed to 'foo'",
      "type": "string",
      "enum": ["foo","bar"],
      "default": "bar"
    },
    "depender1": {
      "title": "I depend on fieldOne to be 'foo'",
      "type": "string",
      "enum": ["lorem","ipsum"],
      "options": {
        "dependencies": {
          "fieldOne": "foo"
        }
      }
    },
    "depender2": {
      "title": "I depend on fieldOne to be 'bar'",
      "type": "string",
      "enum": ["dolor", "sit"],
      "options": {
        "dependencies": {
          "fieldOne": "bar"
        }
      }
    }
  }
}

JSON 模式规范中的 dependencies 关键字不够灵活,无法处理大多数用例, 因此 JSON Editor 引入了几个自定义关键字,在这方面有所帮助。

第一步是让一个字段“观察”其他字段的变化。

{
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string"
    },
    "last_name": {
      "type": "string"
    },
    "full_name": {
      "type": "string",
      "watch": {
        "fname": "first_name",
        "lname": "last_name"
      }
    }
  }
}

关键字 watch 告诉 JSON 编辑器要监视哪些字段发生变化。

键(本例中的 fnamelname)是字段的字母数字别名。

值(first_namelast_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_namelast_name 字段。

Templates

单独观察字段不会做任何事情。 对于上面的示例,您需要告诉 JSON Editor full_name 应该是 fname [space] lname。 JSON Editor 使用 javascript 模板引擎来完成此操作。 默认包含准系统模板引擎(仅限简单的 {{variable}} 替换),但也支持许多最流行的模板引擎:

  • ejs
  • handlebars
  • hogan
  • markup
  • mustache
  • swig
  • underscore >=1.7 (since 1.4.0, see also #332)

您可以通过设置 JSONEditor 更改默认值。 defaults.options.template 到受支持的模板引擎之一:

JSONEditor.defaults.options.template = 'handlebars';

您也可以在每个实例的基础上设置模板引擎:

const 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"
      }
    }
  }
}

也可以将“template”属性设置为 JavaScript 回调函数,在 window.JSONEditor.defaults.callbacks.template 下定义。 在 JavaScript 回调中,您可以访问 watch 属性 + 当前编辑器下定义的所有变量。

示例架构:

{
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string"
    },
    "last_name": {
      "type": "string"
    },
    "full_name": {
      "type": "string",
      "template": "callbackFunction",
      "watch": {
        "fname": "first_name",
        "lname": "last_name"
      }
    }
  }
}

示例回调函数:

window.JSONEditor.defaults.callbacks.template = {
  "callbackFunction": (jseditor,e) => {
    return e.fname + " " + e.lname;
  }
};

Enum Values

另一个常见的依赖项是下拉菜单,其可能的值取决于其他字段。 下面是一个示例:

{
  "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 告诉 JSON 编辑器我们要使用此字段来填充下拉列表。

{
  "primary_color": {
    "type": "string",
    "watch": {
      "colors": "possible_colors"
    },
    "enumSource": "colors"
  }
}

现在,只要 possible_colors 数组发生变化,下拉列表的值也会随之变化。

这是enumSource最基本的用法。 此属性的更详细形式支持 过滤、从多个来源提取、常量值等。 这是一个更复杂的示例(它使用 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}}"
      }]
    }
  }
}

详细形式的所有可选模板都将属性 itemi 传递给它们。 item 指的是数组元素。 i 是从零开始的索引。

JavaScript callbacks

也可以使用 JavaScript 回调函数代替 enumSource 属性的模板:valuetitlefilter

示例架构:

{
  "type": "object",
  "properties": {
    "possible_colors": {
      "type": "array",
      "format": "table",
      "items": {
        "type": "object",
        "properties": {
          "text": {
            "type": "string"
          }
        }
      }
    },
    "primary_color": {
      "type": "string",
      "watch": {
        "colors": "possible_colors"
      },
      "enumSource": [{
        "source": "colors",
        "filter": "enumFilterCB",
        "title": "enumTitleCB",
        "value": "enumValueCB"
      }]
    }
  }
}

示例 JavaScript 回调:

window.JSONEditor.defaults.callbacks.template = {
  "enumFilterCB": (jseditor, e) => {
    if (e.item.text.toLowerCase() == 'red') return ""; // "red" is not allowed
    return e.item.text;
  },
  "enumTitleCB": (jseditor, e) => e.item.text.toUpperCase(),
  "enumValueCB": (jseditor, e) => e.item.text.toLowerCase()
};

Sorting

要对动态 EnumSource 进行排序,您可以将 EnumSource 属性 sort 设置为 ascdesc

Dynamic Headers

模式的 title 关键字用于将用户友好的标头添加到编辑 UI。 但有时,根据其他字段而变化的动态标头会很有帮助。

考虑一组孩子的例子。 如果没有动态标头,数组元素的 UI 将显示 Child 1Child 2 等。 如果标头可以是动态的并包含有关孩子的信息,例如 1 - John(9 岁)2 - Sarah(11 岁),那就更好了。

为此,请使用 headerTemplate 属性。 所有被监视的变量都被传递到这个模板中,连同静态标题 title(例如“Child”)、基于 0 的索引 i0(例如“0”和"1")、基于 1 的索引 i1 和字段的值 self(例如 {"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

如果其中一个包含的模板引擎不够用, 您可以使用任何带有 compile 方法的自定义模板引擎。 例如:

const myengine = {
  compile: template =>
    // Compile should return a render function
    vars => {
      // A real template engine would render the template here
      const result = template;
      return result;
    }
};

// Set globally
JSONEditor.defaults.options.template = myengine;

// Set on a per-instance basis
const editor = new JSONEditor(element,{
  schema: schema,
  template: myengine
});

Language and String Customization

JSON Editor 使用翻译函数在 UI 中生成字符串。 提供了默认的 en 语言映射。

您可以轻松地覆盖默认语言的个别翻译或完全创建您自己的语言映射。

// 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"
};

默认情况下,JSON 编辑器的所有实例都将使用 en 语言。 要覆盖此默认设置,请设置 JSONEditor.defaults.language 属性。

JSONEditor.defaults.language = "es";

Button Custimization

所有按钮都有 json-editor-btntype-* 格式的类名。 使用这些类名,您可以选择按钮是否应隐藏图标或标签。 图标包裹在 I 标签中,标签包裹在 SPAN 标签中。

示例:

隐藏“对象属性”按钮上的图标

.json-editor-btntype-properties i {
  display: none;
}

: 隐藏“对象属性”按钮上的文本:

.json-editor-btntype-properties span {
  display: none;
}

Custom Editor Interfaces

JSON 编辑器包含每个原始 JSON 类型以及一些其他专用类型的编辑器界面。

您可以相当轻松地添加自定义编辑器界面。 查看任何现有的示例。

JSON 编辑器使用解析器函数来确定将哪个编辑器界面用于特定模式或子模式。

假设您制作了一个用于编辑地理数据的自定义 location 编辑器。 您可以添加解析器函数以在适当的时候使用此自定义编辑器。 例如:

// Add a resolver function to the beginning of the resolver list
// This will make it run before any other ones
JSONEditor.defaults.resolvers.unshift(schema => {
  if(schema.type === "object" && schema.format === "location") {
    return "location";
  }

  // If no valid editor is returned, the next resolver function will be used
});

以下模式现在将为每个数组元素使用此自定义编辑器,而不是默认的 object 编辑器。

{
  "type": "array",
  "items": {
    "type": "object",
    "format": "location",
    "properties": {
      "longitude": {
        "type": "number"
      },
      "latitude": {
        "type": "number"
      }
    }
  }
}

如果您创建了一个您认为对其他人有帮助的自定义编辑器界面,请提交拉取请求!

可能性是无止境。 一些想法:

  • A compact way to edit objects
  • Radio button version of the select editor
  • Autosuggest for strings (like enum, but not restricted to those values)
  • Better editor for arrays of strings (tag editor)
  • Canvas based image editor that produces Base64 data URLs

Custom Validation

JSON 编辑器提供了一个连接到验证引擎的钩子,用于添加您自己的自定义验证。

假设您要强制所有 format 设置为 date 的模式与模式 YYYY-MM-DD 匹配。

// Custom validators must return an array of errors or an empty array if valid
JSONEditor.defaults.custom_validators.push((schema, value, path) => {
  const 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;
});

Override Editors Methods

// override class method
JSONEditor.defaults.editors.integer.prototype.sanitize = function(value) {
  return value
}; 

// override object method
var path ="root.integerfield";
editor.getEditor(path).sanitize = function(value) {
  return value
};

Support Legacy Browser (not tested)

JSON Editor 可以与支持 ES5 的浏览器一起使用,但为了将它与旧浏览器(如 IE)一起使用,有必要使用“core-js”作为 polyfill。

<script src="https://unpkg.com/core-js-bundle@latest/minified.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@json-editor/json-editor@latest/dist/jsoneditor.min.js"></script>

JSON Editor

Build Status Fork of the inactive jdorn/json-editor using the updated fork json-editor/json-editor. Some pull requests added from the original repo.

JSON Schema -> HTML Editor -> JSON

JSON Editor takes a JSON Schema and uses it to generate an HTML form. It has full support for JSON Schema version 3 and 4 and can integrate with several popular CSS frameworks (bootstrap, spectre, tailwind).

Check out an interactive demo: https://json-editor.github.io/json-editor/

Or the JSON-Editor Interactive Playground: https://pmk65.github.io/jedemov2/dist/demo.html

Install

Install package

npm install @json-editor/json-editor

Using a CDN

<script src="https://cdn.jsdelivr.net/npm/@json-editor/json-editor@latest/dist/jsoneditor.min.js"></script>

You can also access older releases from CDN, using the landing page: https://www.jsdelivr.com/package/npm/@json-editor/json-editor

For local usage download the production version or the development version

Requirements

JSON Editor has no dependencies. It only needs a modern browser (tested in Chrome and Firefox).

Optional Requirements

The following are not required, but can improve the style and usability of JSON Editor when present.

  • A compatible JS template engine (Mustache, Underscore, Hogan, Handlebars, Lodash, Swig, Markup, or EJS)
  • A compatible CSS framework for styling (Spectre, Tailwind, Bootstrap4)
  • A compatible icon library (Spectre, jQueryUI, Font Awesome 3/4/5)
  • SCEditor for WYSIWYG editing of HTML or BBCode content
  • SimpleMDE for editing of Markdown content
  • Ace Editor for editing code
  • Jodit Open Source WYSIWYG editor
  • Autocomplete Accessible autocomplete component
  • Choices for nicer Select & Array boxes
  • Select2 for nicer Select boxes
  • Selectize for nicer Select & Array boxes
  • Flatpickr lightweight and powerful datetime picker
  • Signature Pad HTML5 canvas based smooth signature drawing
  • Vanilla Picker A simple, easy to use vanilla JS color picker with alpha selection
  • Cleave.js for formatting your <input/> content while you are typing
  • IMask.js vanilla javascript input mask
  • math.js for more accurate floating point math (multipleOf, divisibleBy, etc.)
  • DOMPurify DOM-only, super-fast, uber-tolerant XSS sanitizer. (If you want to use HTML format in titles/headers and descriptions.)

Usage

If you learn best by example, check these out:

  • Basic Usage Example - https://json-editor.github.io/json-editor/basic.html
  • ACE Editor Example - https://json-editor.github.io/json-editor/ace_editor.html
  • Advanced Usage Example - https://json-editor.github.io/json-editor/advanced.html
  • CSS Integration Example - https://json-editor.github.io/json-editor/css_integration.html
  • Base64 Editor Example (Muiltple Upload) - https://json-editor.github.io/json-editor/multipleuploadbase64.html
  • Choices Editor Example - https://json-editor.github.io/json-editor/choices.html
  • Cleave.js Editor Example - https://json-editor.github.io/json-editor/cleave.html
  • Colorpicker Editor Example - https://json-editor.github.io/json-editor/colorpicker.html
  • Datetime Editor Example - https://json-editor.github.io/json-editor/datetime.html
  • DescribedBy Hyperlink Editor Example - https://json-editor.github.io/json-editor/describedby.html
  • iMask.js Editor Example - https://json-editor.github.io/json-editor/imask.html
  • Radio Button JSON Editor Example - https://json-editor.github.io/json-editor/radio.html
  • Recursive JSON Editor Example - https://json-editor.github.io/json-editor/recursive.html
  • Select2 Editor Example - https://json-editor.github.io/json-editor/select2.html
  • Selectize Editor Example - https://json-editor.github.io/json-editor/selectize.html
  • Signature Pad Editor Example - https://json-editor.github.io/json-editor/signature.html
  • Star Rating Editor Example - https://json-editor.github.io/json-editor/starrating.html
  • Upload Editor Example - https://json-editor.github.io/json-editor/upload.html
  • WYSIWYG Editor Example - https://json-editor.github.io/json-editor/wysiwyg.html

More examples can be found at the JSON-Editor Interactive Playground

The rest of this README contains detailed documentation about every aspect of JSON Editor. For more under-the-hood documentation, check the wiki.

Initialize

const element = document.getElementById('editor_holder');

const editor = new JSONEditor(element, options);

Options

Options can be set globally or on a per-instance basis during instantiation.

// Set an option globally
JSONEditor.defaults.options.theme = 'bootstrap4';

// Set an option during instantiation
const editor = new JSONEditor(element, {
  //...
  theme: 'bootstrap4'
});

Here are all the available options:

Option Description Default Value
ajax If true, JSON Editor will load external URLs in $ref via ajax. false
ajaxBase Allows schema references to work either with or without cors; set to protocol://host:port when api is served by different host.
ajaxCredentials If true, JSON Editor will make ajax call with [credentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials). false
compact If true, the label will not be displayed/added. false
disable_array_add If true, remove all "add row" buttons from arrays. false
disable_array_delete If true, remove all "delete row" buttons from arrays. false
disable_array_delete_all_rows If true, remove all "delete all rows" buttons from arrays. false
disable_array_delete_last_row If true, remove all "delete last row" buttons from arrays. false
disable_array_reorder If true, remove all "move up" and "move down" buttons from arrays. false
enable_array_copy If true, add copy buttons to arrays. false
disable_collapse If true, remove all collapse buttons from objects and arrays. false
disable_edit_json If true, remove all Edit JSON buttons from objects. false
disable_properties If true, remove all Edit Properties buttons from objects. false
array_controls_top If true, array controls (add, delete etc) will be displayed at top of list. false
form_name_root The first part of the `name` attribute of form inputs in the editor. An full example name is `root[person][name]` where "root" is the form_name_root. root
iconlib The icon library to use for the editor. See the CSS Integration section below for more info. null
remove_button_labels Display only icons in buttons. This works only if iconlib is set. false
no_additional_properties If true, objects can only contain properties defined with the properties keyword. false
refs An object containing schema definitions for URLs. Allows you to pre-define external schemas. {}
required_by_default If true, all schemas that don't explicitly set the required property will be required. false
keep_oneof_values If true, makes oneOf copy properties over when switching. true
schema A valid JSON Schema to use for the editor. Version 3 and Version 4 of the draft specification are supported. {}
show_errors When to show validation errors in the UI. Valid values are 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 The JS template engine to use. See the Templates and Variables section below for more info. default
theme The CSS theme to use. See the CSS Integration section below for more info. html
display_required_only If true, only required properties will be included by default. false
show_opt_in If true, NON required properties will have an extra toggable checkbox near the title that determines if the value must be included or not in the editor´s value false
prompt_before_delete If true, displays a dialog box with a confirmation message before node deletion. true
object_layout The default value of `format` for objects. If set to table for example, objects will use table layout if `format` is not specified. normal
enum_source_value_auto_select Preserve value at Move Up or Down.(No value is selected automatically upon deletion.) true
max_depth Max depth of the nested properties to be rendered of provided json schema. The missing of this option could cause "maximum call stack size exceeded" in case of object properties with circular references. 0 value means "render all". 0
use_default_values If true default values based on the "type" of the property will be used true

*Note If the ajax property is true and JSON Editor needs to fetch an external url, the api methods won't be available immediately. Listen for the ready event before calling them.

editor.on('ready',() => {
  // Now the api methods will be available
  editor.validate();
});

Get/Set Value

editor.setValue({name: "John Smith"});

const 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
const name = editor.getEditor('root.name');

// `getEditor` will return null if the path is invalid
if (name) {
  name.setValue("John Smith");

  console.log(name.getValue());
}

Validate

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
const 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
const errors = editor.validate({
  value: {
    to: "test"
  }
});

Listen for Changes

The change event is fired whenever the editor's value changes.

editor.on('change',() => {
  // Do something
});

editor.off('change',function_reference);

You can also watch a specific field for changes:

editor.watch('path.to.field',() => {
  // Do something
});

editor.unwatch('path.to.field',function_reference);

Or watch all fields (Similar to the "onchange" event, but tracks the field changed)

const watcherCallback = function (path) {
  console.log(`field with path: [${path}] changed to [${JSON.stringify(this.getEditor(path).getValue())}]`);
  // Do something
}
for (let key in editor.editors) {
  if (editor.editors.hasOwnProperty(key) && key !== 'root') {
    editor.watch(key, watcherCallback.bind(editor, key));
  }
}

Enable and Disable the Editor

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!");

// Activate part of the form
editor.activate();

// Deactivate part of the form
editor.deactivate();

Destroy

This removes the editor HTML from the DOM and frees up resources.

editor.destroy();

CSS Integration

JSON Editor can integrate with several popular CSS frameworks out of the box.

The currently supported themes are:

  • barebones
  • html (the default)
  • bootstrap4
  • spectre
  • tailwind

Note: The following themes have NOT been updated to 2.x format and will be removed in final version unless there's someone willing to update those. Old 1.x themes displays the message "This is an old JSON-Editor 1.x Theme and might not display elements correctly when used with the 2.x version" at the bottom of the form output.

  • bootstrap2
  • bootstrap3
  • foundation3
  • foundation4
  • foundation5
  • foundation6
  • jqueryui
  • materialize

The default theme is html, which does not rely on an external framework. This default can be changed by setting the JSONEditor.defaults.options.theme variable.

If you want to specify your own styles with CSS, you can use barebones, which includes almost no classes or inline styles.

JSONEditor.defaults.options.theme = 'spectre';

You can override this default on a per-instance basis by passing a theme parameter in when initializing:

const editor = new JSONEditor(element,{
  schema: schema,
  theme: 'tailwind'
});

Icon Libraries

JSON Editor also supports several popular icon libraries. The icon library must be set independently of the theme, even though there is some overlap.

The supported icon libs are:

  • jqueryui
  • fontawesome3
  • fontawesome4
  • fontawesome5
  • spectre

By default, no icons are used. Just like the CSS theme, you can set the icon lib globally or when initializing:

// Set the global default
JSONEditor.defaults.options.iconlib = "spectre";

// Set the icon lib during initialization
const editor = new JSONEditor(element,{
  schema: schema,
  iconlib: "fontawesome4"
});

It's possible to create your own custom themes and/or icon libs as well. Look at any of the existing classes for examples.

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.

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/",
      // Optional - set CSS classes for the link
      "class": "comment-link open-in-modal primary-text"
    }
  ]
}

Make link download when clicked

{
  "title": "Document filename",
  "type": "string",
  "links": [
    {
      "rel": "Download File",
      "href": "/documents/{{self}}",
      // Can also set `download` to a string as per the HTML5 spec
      "download": true
    }
  ]
}

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.

Property Ordering

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:

  1. prop4 (order 1)
  2. prop2 (order 10)
  3. prop1 (order 1000)
  4. prop3 (order 1001)

Default Properties

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.

format

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
  • email
  • month
  • password
  • number
  • range
  • tel
  • text
  • textarea
  • time
  • url
  • week

Here is an example that will show a color picker in browsers that support it:

{
  "type": "object",
  "properties": {
    "color": {
      "type": "string",
      "format": "color"
    }
  }
}

String Editors Input Attributes

You can set custom attributes such as placeholder, class and data- on the input field using the special options keyword inputAttributes.

Like this:

{
  "type": "object",
  "properties": {
    "name": {
      "title": "Full Name",
      "options": {
        "inputAttributes": {
          "placeholder":  "your name here...",
          "class": "myclass"
        }
      }
    }
  }
}

Specialized String Editors

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
  }
}

SimpleMDE is a simple Markdown editor with live preview. To use it, set the format to markdown:

{
  "type": "string",
  "format": "markdown"
}

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
  • groovy
  • 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 enable Ace editor options individually by setting the options.ace in schema.

{
  "type": "string",
  "format": "sql",
  "options": {
    "ace": {
      "theme": "ace/theme/vibrant_ink",
      "tabSize": 2,
      "useSoftTabs": true,
      "wrap": true
    }
  }
}

Booleans

The default boolean editor is a select box with options "true" and "false". To use a checkbox instead, set the format to checkbox.

{
  "type": "boolean",
  "format": "checkbox"
}

Arrays

The default array editor takes up a lot of screen real estate. The table and tabs formats provide more compact UIs for editing arrays.

The table format works great when every array element has the same schema and is not too complex.

The tabs format can handle any array, but only shows one array element at a time. It has tabs on the left for switching between items.

The tabs-top format place tabs on the top.

Here's an example of the table format:

{
  "type": "array",
  "format": "table",
  "items": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string"
      }
    }
  }
}

For arrays of enumerated strings, you can also use the select or checkbox format. These formats require a very specific schema to work:

{
  "type": "array",
  "uniqueItems": true,
  "items": {
    "type": "string",
    "enum": ["value1","value2"]
  }
}

By default, the checkbox editor (multiple checkboxes) will be used if there are fewer than 8 enum options. Otherwise, the select editor (a multiselect box) will be used.

You can override this default by passing in a format:

{
  "type": "array",
  "format": "select",
  "uniqueItems": true,
  "items": {
    "type": "string",
    "enum": ["value1","value2"]
  }
}

Array events

When an array item is added, removed, moved up, moved or removed the json editor will trigger a relative event.

editor.on('moveRow', editor => {
  console.log('moveRow', editor)
});
editor.on('addRow', editor => {
  console.log('addRow', editor)
});
editor.on('deleteRow', editor => {
  console.log('deleteRow', editor)
});
editor.on('deleteAllRows', editor => {
  console.log('deleteAllRows', editor)
});

Objects

The default object layout is one child editor per row. The grid format will instead put multiple child editors per row. This can make the editor much more compact, but at a cost of not guaranteeing child editor order. This format will stretch columns to fill gaps untill all the 12 columns are filled.

{
  "type": "object",
  "properties": {
    "name": { "type": "string" }
  },
  "format": "grid"
}

The grid-strict format instead will respect columns sizes (no stretching) and properties order. It introduces the new grid-break property to breaks the current row leaving a 4 colums gap.

{
  "type": "object",
  "format": "grid-strict",
  "properties": {
    "a": {
      "title": "a",
      "type": "string",
      "options": {
        "grid_columns": 4
      }
    },
    "b": {
      "title": "b",
      "type": "string",
      "options": {
        "grid_columns": 4,
        "grid_break": true
      }
    },
    "c": {
      "title": "c",
      "type": "string",
      "options": {
        "grid_columns": 6
      }
    },
    "d": {
      "title": "d",
      "type": "string",
      "options": {
        "grid_columns": 6
      }
    }
  }
}

The categories format groups properties in top-tabbed panels, one for each object or array property plus one that groups all added or other types of properties. Panel tabs titles came from object or array titles and for the grouping panel it defaults to "Basic", unless basicCategoryTitle is defined.

{
  "type": "object",
  "properties": {
    "name": { "type": "string" }
  },
  "format": "categories",
  "basicCategoryTitle": "Main"
}

Demo page will look like this:

Categories format

Editor Options

Editors can accept options which alter the behavior in some way.

  • collapsed - If set to true, the editor will start collapsed (works for objects and arrays)
  • disable_array_add - If set to true, the "add row" button will be hidden (works for arrays)
  • disable_array_delete - If set to true, all of the "delete" buttons will be hidden (works for arrays)
  • disable_array_delete_all_rows - If set to true, just the "delete all rows" button will be hidden (works for arrays)
  • disable_array_delete_last_row - If set to true, just the "delete last row" buttons will be hidden (works for arrays)
  • disable_array_reorder - If set to true, the "move up/down" buttons will be hidden (works for arrays)
  • disable_collapse - If set to true, the collapse button will be hidden (works for objects and arrays)
  • disable_edit_json - If set to true, the Edit JSON button will be hidden (works for objects)
  • disable_properties - If set to true, the Edit Properties button will be hidden (works for objects)
  • array_controls_top - If set to true, array controls (add, delete etc) will be displayed at top of list (works for arrays)
  • enum_titles - An array of display values to use for select box options in the same order as defined with the enum keyword. Works with schema using enum values.
  • expand_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 - If set to true, the editor will not appear in the UI (works for all types)
  • input_height - Explicitly set the height of the input element. Should be a valid CSS width string (e.g. "100px"). Works best with textareas.
  • input_width - Explicitly set the width of the input element. Should be a valid CSS width string (e.g. "100px"). Works for string, number, and integer data types.
  • remove_empty_properties - If set to true for an object, empty object properties (i.e. those with falsy values) will not be returned by getValue().
{
  "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;

InfoText

Using the option infoText, will create a info button, displaying the text you set, on hovering.

{
  "type": "string",
  "title": "Name",
  "options": {
    "infoText": "Your full name"
  }
}

Dependencies

Sometimes, it's necessary to have one field's value depend on another's.

The dependency information is fetched from the dependencies field in the options field of the control. The dependencies field should be a map where the keys are the names of the fields depended on and the value is the expected value. The value may be an array to indicate multiple value possibilities. This uses the internal field value watch system to notify fields of changes in their dependencies.

Here's an example schema:

{
  "title": "An object",
  "type": "object",
  "properties": {
    "fieldOne": {
      "title": "I should be changed to 'foo'",
      "type": "string",
      "enum": ["foo","bar"],
      "default": "bar"
    },
    "depender1": {
      "title": "I depend on fieldOne to be 'foo'",
      "type": "string",
      "enum": ["lorem","ipsum"],
      "options": {
        "dependencies": {
          "fieldOne": "foo"
        }
      }
    },
    "depender2": {
      "title": "I depend on fieldOne to be 'bar'",
      "type": "string",
      "enum": ["dolor", "sit"],
      "options": {
        "dependencies": {
          "fieldOne": "bar"
        }
      }
    }
  }
}

The dependencies keyword from the JSON Schema specification is not nearly flexible enough to handle most use cases, so JSON Editor introduces a couple custom keywords that help in this regard.

The first step is to have a field "watch" other fields for changes.

{
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string"
    },
    "last_name": {
      "type": "string"
    },
    "full_name": {
      "type": "string",
      "watch": {
        "fname": "first_name",
        "lname": "last_name"
      }
    }
  }
}

The keyword watch tells JSON Editor which fields to watch for changes.

The keys (fname and lname in this example) are alphanumeric aliases for the fields.

The values (first_name and last_name) are paths to the fields. To access nested properties of objects, use a dot for separation (e.g. "path.to.field").

By default paths are from the root of the schema, but you can make the paths relative to any ancestor node with a schema id defined as well. This is especially useful within arrays. Here's an example:

{
  "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"
        }
      }
    }
  }
}

Now, the full_name field in each array element will watch the first_name and last_name fields within the same array element.

Templates

Watching fields by itself doesn't do anything. For the example above, you need to tell JSON Editor that full_name should be fname [space] lname. JSON Editor uses a javascript template engine to accomplish this. A barebones template engine is included by default (simple {{variable}} replacement only), but many of the most popular template engines are also supported:

  • ejs
  • handlebars
  • hogan
  • markup
  • mustache
  • swig
  • underscore >=1.7 (since 1.4.0, see also #332)

You can change the default by setting JSONEditor.defaults.options.template to one of the supported template engines:

JSONEditor.defaults.options.template = 'handlebars';

You can set the template engine on a per-instance basis as well:

const editor = new JSONEditor(element,{
  schema: schema,
  template: 'hogan'
});

Here is the completed full_name example using the default barebones template engine:

{
  "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"
      }
    }
  }
}

It is also possible to set the "template" property to a JavaScript callback function, defined under window.JSONEditor.defaults.callbacks.template. Inside the JavaScript callback, you have access to all the variables defined under the watch property + the current editor.

Example Schema:

{
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string"
    },
    "last_name": {
      "type": "string"
    },
    "full_name": {
      "type": "string",
      "template": "callbackFunction",
      "watch": {
        "fname": "first_name",
        "lname": "last_name"
      }
    }
  }
}

Example Callback function:

window.JSONEditor.defaults.callbacks.template = {
  "callbackFunction": (jseditor,e) => {
    return e.fname + " " + e.lname;
  }
};

Enum Values

Another common dependency is a drop down menu whose possible values depend on other fields. Here's an example:

{
  "type": "object",
  "properties": {
    "possible_colors": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "primary_color": {
      "type": "string"
    }
  }
}

Let's say you want to force primary_color to be one of colors in the possible_colors array. First, we must tell the primary_color field to watch the possible_colors array.

{
  "primary_color": {
    "type": "string",
    "watch": {
      "colors": "possible_colors"
    }
  }
}

Then, we use the special keyword enumSource to tell JSON Editor that we want to use this field to populate a drop down.

{
  "primary_color": {
    "type": "string",
    "watch": {
      "colors": "possible_colors"
    },
    "enumSource": "colors"
  }
}

Now, anytime the possible_colors array changes, the dropdown's values will be changed as well.

This is the most basic usage of enumSource. The more verbose form of this property supports filtering, pulling from multiple sources, constant values, etc.. Here's a more complex example (this uses the Swig template engine syntax to show some advanced features)

{
  // 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"]
  ]
}

You can also specify a list of static items with a slightly different syntax:

{
  "enumSource": [{
      // A watched field source
      "source": [
        {
          "value": 1,
          "title": "One"
        },
        {
          "value": 2,
          "title": "Two"
        }
      ],
      "title": "{{item.title}}",
      "value": "{{item.value}}"
    }]
  ]
}

The colors examples used an array of strings directly. Using the verbose form, you can also make it work with an array of objects. Here's an example:

{
  "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}}"
      }]
    }
  }
}

All of the optional templates in the verbose form have the properties item and i passed into them. item refers to the array element. i is the zero-based index.

JavaScript callbacks

It is also possible to use JavaScript callback functions instead of templates for the enumSource properties properties: value, title and filter.

Example Schema:

{
  "type": "object",
  "properties": {
    "possible_colors": {
      "type": "array",
      "format": "table",
      "items": {
        "type": "object",
        "properties": {
          "text": {
            "type": "string"
          }
        }
      }
    },
    "primary_color": {
      "type": "string",
      "watch": {
        "colors": "possible_colors"
      },
      "enumSource": [{
        "source": "colors",
        "filter": "enumFilterCB",
        "title": "enumTitleCB",
        "value": "enumValueCB"
      }]
    }
  }
}

Example JavaScript callbacks:

window.JSONEditor.defaults.callbacks.template = {
  "enumFilterCB": (jseditor, e) => {
    if (e.item.text.toLowerCase() == 'red') return ""; // "red" is not allowed
    return e.item.text;
  },
  "enumTitleCB": (jseditor, e) => e.item.text.toUpperCase(),
  "enumValueCB": (jseditor, e) => e.item.text.toLowerCase()
};

Sorting

To sort the dynamic EnumSource, you can set the EnumSource property sort to either asc or desc.

Dynamic Headers

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:

const myengine = {
  compile: template =>
    // Compile should return a render function
    vars => {
      // A real template engine would render the template here
      const result = template;
      return result;
    }
};

// Set globally
JSONEditor.defaults.options.template = myengine;

// Set on a per-instance basis
const 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";

Button Custimization

All buttons have classnames in the format json-editor-btntype-*. Using these classnames you can choose if the button should have icon or label hidden. The icon is wrapped in an I tag, the label is wrapped in a SPAN tag.

Examples:

Hide the icon on "Object Properties" button:

.json-editor-btntype-properties i {
  display: none;
}

Hide the text on "Object Properties" button:

.json-editor-btntype-properties span {
  display: none;
}

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(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"
      }
    }
  }
}

If you create a custom editor interface that you think could be helpful to others, submit a pull request!

The possibilities are endless. Some ideas:

  • A compact way to edit objects
  • Radio button version of the select editor
  • Autosuggest for strings (like enum, but not restricted to those values)
  • Better editor for arrays of strings (tag editor)
  • Canvas based image editor that produces Base64 data URLs

Custom Validation

JSON Editor provides a hook into the validation engine for adding your own custom validation.

Let's say you want to force all schemas with format set to date to match the pattern YYYY-MM-DD.

// Custom validators must return an array of errors or an empty array if valid
JSONEditor.defaults.custom_validators.push((schema, value, path) => {
  const 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;
});

Override Editors Methods

// override class method
JSONEditor.defaults.editors.integer.prototype.sanitize = function(value) {
  return value
}; 

or

// override object method
var path ="root.integerfield";
editor.getEditor(path).sanitize = function(value) {
  return value
};

Support Legacy Browser (not tested)

JSON Editor can be used with browsers that support ES5, but in order to use it with older browsers such as IE, it is necessary to use "core-js" as a polyfill.

<script src="https://unpkg.com/core-js-bundle@latest/minified.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@json-editor/json-editor@latest/dist/jsoneditor.min.js"></script>
更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文