### Install Dependencies
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/react_demo/README.md
Installs all necessary project dependencies using the Node Package Manager (npm). This command should be run once before starting the application.
```bash
npm install
```
--------------------------------
### Install Dependencies
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/react_advanced_demo/README.md
Installs all necessary project dependencies using the npm package manager. This command should be run once before starting the application.
```bash
npm install
```
--------------------------------
### Full JSONEditor Example (HTML/JavaScript)
Source: https://github.com/josdejong/jsoneditor/blob/develop/docs/usage.md
A complete HTML page demonstrating the setup, initialization, and usage of JSONEditor with buttons to set and get JSON data.
```html
```
--------------------------------
### Initialize JSONEditor with Schema and Options
Source: https://github.com/josdejong/jsoneditor/blob/develop/test/test_schema.html
This snippet shows the complete setup for a JSONEditor instance. It defines the container, JSON schema, editor options (including modes, schema references, and event handlers like onError and onChange), and initial JSON data. The onChange handler includes validation logic.
```javascript
var container = document.getElementById('jsoneditor');
var schema = {
"title": "User",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"gender": {
"enum": ["male", "female"]
},
"age": {
"description": "Age in years",
"examples": [18, 65],
"type": "integer",
"minimum": 0
},
"hobbies": {
"$ref": "hobbies.json"
}
},
"required": ["firstName", "lastName"]
};
var hobbiesSchema = {
"type": "array",
"items": {
"type": "string"
}
};
var options = {
mode: 'code',
modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
schema: schema,
schemaRefs: {"hobbies.json": hobbiesSchema},
onError: function (err) {
console.error('ERROR', err);
},
onChange: async () => {
const errors = await editor.validate()
if (errors.length === 0) {
console.log('validation errors: NONE')
// do something, like persisting the JSON
} else {
// show error to the user or something
console.log('validation errors', errors)
}
}
};
var json = {
"firstName": "Jos",
"lastName": "de Jong",
"gender": null,
"age": 34.2,
"hobbies": [
"programming",
"movies",
"bicycling"
]
};
var editor = new JSONEditor(container, options, json);
console.log('json', json);
console.log('schema', schema);
```
--------------------------------
### JSONEditor Constructor and Options
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/02_viewer.html
Documentation for the JSONEditor constructor and its configuration options, particularly the 'mode' parameter for viewer functionality.
```APIDOC
JSONEditor(container, options, json)
- Constructor for the JSONEditor.
- Parameters:
- container: HTMLElement | string
The DOM element or its ID where the editor will be created.
- options: object
Configuration options for the editor.
- mode: string
Specifies the editor mode. Common values include 'tree', 'view', 'form'.
'view' or 'viewer' mode makes the editor read-only.
Example: { mode: 'view' }
- json: object | array
The JSON data to be displayed or edited in the editor.
- Returns:
- JSONEditor instance
- Related Methods:
- JSONEditor.destroy()
Cleans up the editor instance.
```
--------------------------------
### Run Demo Server
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/react_demo/README.md
Starts the development server for the JSONEditor React demo. This command will typically open the application in a web browser at http://localhost:3000.
```bash
npm start
```
--------------------------------
### Install JSON Editor with npm
Source: https://github.com/josdejong/jsoneditor/blob/develop/README.md
Installs the JSON Editor library using npm, the recommended package manager. This command fetches and installs the latest version of the library into your project's node_modules directory.
```Shell
npm install jsoneditor
```
--------------------------------
### Build JSONEditor from Source
Source: https://github.com/josdejong/jsoneditor/blob/develop/README.md
Provides npm commands to install dependencies, build the JSONEditor library, and set up automatic rebuilding on file changes.
```bash
npm install
npm run build
npm start
```
--------------------------------
### Run Demo
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/react_advanced_demo/README.md
Starts the development server for the JSONEditor React advanced demo. This command will typically open the demo in a web browser at http://localhost:3000.
```bash
npm start
```
--------------------------------
### JSONEditor Initialization and Usage
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/requirejs_demo/requirejs_demo.html
Demonstrates how to initialize JSONEditor with Require.js and use its core functions to set and get JSON data. This snippet assumes a Require.js setup where JSONEditor is properly loaded.
```javascript
require(['jsoneditor'], function(JSONEditor) {
// Create a JSONEditor instance
var container = document.getElementById('jsoneditor');
var options = {
// Editor options can be set here
// For example:
// mode: 'tree',
// modes: ['tree', 'code', 'form', 'view'],
// onChange: function() {
// console.log('JSON changed');
// }
};
var editor = new JSONEditor(container, options);
// Set JSON data
var json = {
"name": "Example",
"version": "1.0.0"
};
editor.set(json);
// Get JSON data
var updatedJson = editor.get();
console.log('Current JSON:', updatedJson);
// Example of setting JSON via a button click (assuming a button with id 'setJsonBtn')
document.getElementById('setJsonBtn').addEventListener('click', function() {
var newJson = {
"message": "Hello World",
"status": "success"
};
editor.set(newJson);
});
// Example of getting JSON via a button click (assuming a button with id 'getJsonBtn')
document.getElementById('getJsonBtn').addEventListener('click', function() {
var currentJson = editor.get();
console.log('JSON retrieved from button click:', currentJson);
alert('Current JSON: ' + JSON.stringify(currentJson, null, 2));
});
});
```
--------------------------------
### JSONEditor Dynamic Autocomplete Setup
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/12_autocomplete_dynamic.html
Initializes a JSONEditor instance with dynamic autocomplete enabled. The autocomplete options are dynamically generated by extracting unique words from the editor's JSON content. This requires the JSONEditor library and Lodash (`_`).
```javascript
// create the editor
const container = document.getElementById('jsoneditor')
const options = {
autocomplete: {
applyTo: ['value'],
filter: 'contain',
trigger: 'focus',
getOptions: function (text, path, input, editor) {
return new Promise(function (resolve, reject) {
const options = extractUniqueWords(editor.get())
if (options.length > 0) {
resolve(options)
} else {
reject()
}
})
}
}
}
// helper function to extract all unique words in the keys and values of a JSON object
function extractUniqueWords (json) {
return _.uniq(_.flatMapDeep(json, function (value, key) {
return _.isObject(value) ? [key] : [key, String(value)]
}))
}
const json = {
'array': [{'field1':'v1', 'field2':'v2'}, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
}
const editor = new JSONEditor(container, options, json)
```
--------------------------------
### Initialize JSONEditor (JavaScript)
Source: https://github.com/josdejong/jsoneditor/blob/develop/docs/usage.md
After the DOM is loaded, get the container element by its ID and instantiate the JSONEditor. Options can be passed during initialization.
```javascript
var container = document.getElementById("jsoneditor");
var options = {
mode: 'tree'
};
var editor = new JSONEditor(container, options);
```
--------------------------------
### JSONEditor Initialization and Options
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/08_custom_ace.html
Provides details on the JSONEditor constructor and its core configuration options, particularly for integrating a custom Ace editor. It outlines the structure of the options object and the expected JSON data.
```APIDOC
JSONEditor(container, options, json)
Initializes a new JSONEditor instance.
Parameters:
container: HTMLElement | string
The DOM element or its ID where the editor will be rendered.
options: object
Configuration options for the editor.
- modes: string[]
An array of strings specifying the available modes for the editor (e.g., 'text', 'code', 'tree').
- mode: string
The initial mode the editor should start in (e.g., 'code').
- ace: object
An object representing the custom Ace editor instance to be used. This is crucial for custom Ace integration.
json: object | Array | string
The initial JSON data to load into the editor.
Example Usage:
const container = document.getElementById('editor-container');
const editorOptions = {
modes: ['code', 'tree'],
mode: 'code',
ace: customAceEditorInstance // Assuming customAceEditorInstance is loaded
};
const initialJsonData = { "key": "value" };
const editor = new JSONEditor(container, editorOptions, initialJsonData);
Default Ace Plugins:
When 'mode: code' is used, JSONEditor typically loads:
- ace/mode/json
- ace/ext/searchbox
- ace/theme/jsoneditor
These plugins must be available in the custom Ace editor's path or loaded via script tags.
```
--------------------------------
### Initialize JSONEditor with Options
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/09_readonly_text_mode.html
This snippet shows how to initialize the JSONEditor with specific configurations. It includes setting the initial mode, defining allowed modes, and providing callbacks for editable nodes and mode changes. The example also defines the JSON data to be loaded into the editor.
```css
body {
font: 10.5pt arial;
color: #4d4d4d;
line-height: 150%;
width: 500px;
}
code {
background-color: #f5f5f5;
}
#jsoneditor {
width: 500px;
height: 500px;
}
```
```javascript
const container = document.getElementById('jsoneditor');
const options = {
mode: 'text',
modes: ['text', 'code'],
onEditable: function (node) {
// In modes code and text, node is empty: no path, field, or value
// returning false makes the text area read-only
if (!node.path) {
return false;
}
},
onModeChange: function (newMode, oldMode) {
console.log('Mode switched from', oldMode, 'to', newMode);
}
};
const json = {
"array": [1, 2, 3],
"boolean": true,
"null": null,
"number": 123,
"object": {"a": "b", "c": "d"},
"string": "Hello World"
};
const editor = new JSONEditor(container, options, json);
```
--------------------------------
### Create JSONEditor Viewer
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/02_viewer.html
Initializes a read-only JSONEditor instance. Requires the JSONEditor library and a container element. Takes options and JSON data as input.
```javascript
const container = document.getElementById('jsoneditor')
const options = {
mode: 'view'
}
const json = {
'array': [1, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
}
const editor = new JSONEditor(container, options, json)
```
--------------------------------
### Initialize JSONEditor
Source: https://github.com/josdejong/jsoneditor/blob/develop/test/test_build_min.html
Demonstrates the initialization of the JSONEditor. It requires a DOM container element, configuration options including the initial mode and allowed modes, and the JSON data to be displayed. The `onError` callback is also shown for handling errors.
```javascript
var container, options, json, editor;
container = document.getElementById('jsoneditor');
options = {
mode: 'tree',
modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
onError: function (err) {
alert(err.toString());
}
};
json = {
"array": [1, 2, 3],
"boolean": true,
"color": "#82b92c",
"null": null,
"number": 123,
"object": {"a": "b", "c": "d"},
"string": "Hello World"
};
editor = new JSONEditor(container, options, json);
```
--------------------------------
### Initialize JSONEditor
Source: https://github.com/josdejong/jsoneditor/blob/develop/test/test_minimalist_min.html
Demonstrates the initialization of the JSONEditor. It requires a DOM container element, configuration options including the initial mode and allowed modes, and the JSON data to be displayed. The `onError` callback is also shown for handling errors.
```javascript
var container, options, json, editor;
container = document.getElementById('jsoneditor');
options = {
mode: 'tree',
modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
onError: function (err) {
alert(err.toString());
}
};
json = {
"array": [1, 2, 3],
"boolean": true,
"color": "#82b92c",
"null": null,
"number": 123,
"object": {"a": "b", "c": "d"},
"string": "Hello World"
};
editor = new JSONEditor(container, options, json);
```
--------------------------------
### JSONEditor Tree Mode Example
Source: https://github.com/josdejong/jsoneditor/blob/develop/docs/api.md
Demonstrates how to initialize and use the JSONEditor in 'tree' mode. It shows setting options, loading JSON data, and expanding all nodes.
```javascript
var options = {
"mode": "tree",
"search": true
};
var editor = new JSONEditor(container, options);
var json = {
"Array": [1, 2, 3],
"Boolean": true,
"Null": null,
"Number": 123,
"Object": {"a": "b", "c": "d"},
"String": "Hello World"
};
editor.set(json);
editor.expandAll();
var json = editor.get(json);
```
--------------------------------
### Test Published Library
Source: https://github.com/josdejong/jsoneditor/blob/develop/misc/how_to_publish.md
Installs the newly published version of jsoneditor locally in a temporary directory to verify its functionality. This ensures the npm package works as expected.
```shell
cd tmp-folder
npm install jsoneditor
```
--------------------------------
### Update Dependencies
Source: https://github.com/josdejong/jsoneditor/blob/develop/misc/how_to_publish.md
Installs project dependencies and updates the package-lock.json file. This is a standard step after modifying package.json.
```shell
npm install
```
--------------------------------
### JSONEditor Text Mode Example
Source: https://github.com/josdejong/jsoneditor/blob/develop/docs/api.md
Demonstrates how to initialize and use the JSONEditor in 'text' mode. It shows setting options, including indentation, and loading JSON data.
```javascript
var options = {
"mode": "text",
"indentation": 2
};
var editor = new JSONEditor(container, options);
var json = {
"Array": [1, 2, 3],
"Boolean": true,
"Null": null,
"Number": 123,
"Object": {"a": "b", "c": "d"},
"String": "Hello World"
};
editor.set(json);
var json = editor.get();
```
--------------------------------
### JSONEditor with Custom Ace Editor
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/08_custom_ace.html
Demonstrates initializing JSONEditor with a custom Ace editor instance. It shows how to configure modes and pass the Ace object. Requires the Ace editor library to be loaded separately.
```javascript
const container = document.getElementById('jsoneditor')
const options = {
modes: ['text', 'code', 'tree', 'form', 'view'],
mode: 'code',
ace: ace
}
const json = {
'array': [1, 2, 3],
'boolean': true,
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
}
const editor = new JSONEditor(container, options, json)
```
--------------------------------
### Framework Integration Options
Source: https://github.com/josdejong/jsoneditor/blob/develop/HISTORY.md
New options `onChangeJSON` and `onChangeText` are introduced for easier integration with frameworks. The library is now described as framework-friendly, with React examples provided.
```javascript
const editor = new JSONEditor(container, {
onChangeJSON: function(json) {
console.log('JSON changed:', json);
// Update application state with new JSON
},
onChangeText: function(jsonString) {
console.log('Text changed:', jsonString);
// Update application state with new JSON string
}
});
```
--------------------------------
### JSONEditor API
Source: https://github.com/josdejong/jsoneditor/blob/develop/test/test_update.html
Documentation for the JSONEditor library, focusing on its core methods for initialization and content manipulation. This includes the constructor and methods for updating the editor's state.
```APIDOC
JSONEditor
__constructor__(container: HTMLElement, options?: object, json?: object | Array): JSONEditor
Initializes a new JSONEditor instance.
Parameters:
- container: The HTML element where the editor will be rendered.
- options: An object to configure the editor's behavior and appearance (e.g., mode, allowed modes).
- json: The initial JSON data to load into the editor.
Returns: A new JSONEditor instance.
update(json: object | Array): void
Updates the entire content of the JSONEditor with new JSON data.
Parameters:
- json: The new JSON data to set in the editor.
updateText(jsonString: string): void
Updates the content of the JSONEditor by parsing a JSON string.
Parameters:
- jsonString: A string containing valid JSON data.
expandAll(): void
Expands all nodes in the JSON tree view.
collapseAll(): void
Collapses all nodes in the JSON tree view.
```
--------------------------------
### JSONEditor Basic Initialization and Options
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/21_customize_context_menu.html
Demonstrates the fundamental setup of a JSONEditor instance within a container element. It includes defining editor options, such as the onCreateMenu callback for context menu customization, and initializing the editor with JSON data.
```javascript
const container = document.getElementById('jsoneditor')
const options = {
// onCreateMenu allows us to register a call back function to customise
// the context menu. The callback accpets two parameters, items and path.
// Items is an array containing the current menu items, and path
// (if present) contains the path of the current node (as an array).
// The callback should return the modified (or unmodified) list of menu
// items.
// Every time the user clicks on a context menu button, the menu
// is created from scratch and this callback is called.
onCreateMenu: function (items, node) {
const path = node.path
// log the current items and node for inspection
console.log('items:', items, 'node:', node)
// We are going to add a menu item which returns the current node path
// as a jq path selector ( https://stedolan.github.io/jq/ ). First we
// will create a function, and then We will connect this function to
// the menu item click property in a moment.
function pathTojq() {
let pathString = ''
path.forEach(function (segment, index) {
// path is an array, loop through it
if (typeof segment == 'number') {
// format the selector for array indexs ...
pathString += '\[' + segment + '\]'
} else {
// ... or object keys
pathString += '\"' + segment + '\"'
}
})
alert(pathString) // show it to the user.
}
// Create a new menu item. For our example, we only want to do this
// if there is a path (in the case of appendnodes (for new objects)
// path is null until a node is created)
if (path) {
// Each item in the items array represents a menu item,
// and requires the following details :
items.push({
text: 'jq Path', // the text for the menu item
title: 'Show the jq path for this node', // the HTML title attribute
className: 'example-class', // the css class name(s) for the menu item
click: pathTojq // the function to call when the menu item is clicked
})
}
// Now we will iterate through the menu items, which includes the items
// created by jsoneditor, and the new item we added above. In this
// example we will just alter the className property for the items, but
// you can alter any property (e.g. the click callback, text property etc.)
// for any item, or even delete the whole menu item.
items.forEach(function (item, index, items) {
if ("submenu" in item) {
// if the item has a submenu property, it is a submenu heading
// and contains another array of menu items. Let's colour
// that yellow...
items[index].className += ' submenu-highlight'
} else {
// if it's not a submenu heading, let's make it colorful
items[index].className += ' rainbow'
}
})
// note that the above loop isn't recursive, so it only alters the classes
// on the top-level menu items. To also process menu items in submenus
// you should iterate through any "submenu" arrays of items if the item has one.
// next, just for fun, let's remove any menu separators (again just at the
// top level menu). A menu separator is an item with a type : 'separator'
// property
items = items.filter(function (item) {
return item.type !== 'separator'
})
// finally we need to return the items array. If we don't, the menu
// will be empty.
return items
}
}
const json = {
'array': [1, 2, 3],
'boolean': true,
'color': '#82b92c',
'null': null,
'number': 123,
'object': {'a': 'b', 'c': 'd'},
'string': 'Hello World'
}
const editor = new JSONEditor(container, options, json)
```
--------------------------------
### JSONEditor API Methods and Configuration
Source: https://github.com/josdejong/jsoneditor/blob/develop/test/test_schema.html
This section details the core methods and configuration options available for interacting with a JSONEditor instance. It covers setting the editor mode, validating content against a schema, and handling initialization options.
```APIDOC
JSONEditor API:
// Constructor
new JSONEditor(container: HTMLElement, options: object, json: object)
- Initializes a new JSONEditor instance.
- Parameters:
- container: The DOM element where the editor will be rendered.
- options: An object containing configuration settings for the editor.
- json: The initial JSON data to load into the editor.
// Methods:
setMode(mode: string)
- Switches the editor to the specified mode.
- Supported modes: 'code', 'form', 'text', 'tree', 'view', 'preview'.
- Example:
editor.setMode('form');
validate(): Promise>
- Validates the current JSON content against the provided schema.
- Returns a Promise that resolves with an array of validation errors.
- An empty array indicates no errors.
- Example:
const errors = await editor.validate();
if (errors.length === 0) { console.log('Valid'); } else { console.log('Invalid', errors); }
// Options:
mode: string
- The initial mode of the editor (e.g., 'code', 'form').
modes: Array
- An array of strings specifying which modes are allowed for the editor.
schema: object
- A JSON schema object used for validation and defining the editor's structure.
schemaRefs: object
- An object mapping schema URIs to their corresponding schema definitions, used for resolving $ref pointers.
onError: function(err: object)
- A callback function that is executed when an error occurs within the editor.
onChange: function()
- A callback function that is executed whenever the JSON content in the editor changes. It can be an async function to perform asynchronous operations like validation.
```
--------------------------------
### Load JSONEditor Assets (HTML)
Source: https://github.com/josdejong/jsoneditor/blob/develop/docs/usage.md
Include the JSONEditor CSS and JavaScript files in your HTML head. Ensure the paths correctly point to the library's location or CDN.
```html
```
--------------------------------
### Basic HTML Structure for JSONEditor
Source: https://github.com/josdejong/jsoneditor/blob/develop/test/test_schema.html
This snippet shows the minimal HTML required to host the JSONEditor. It includes a div with the ID 'jsoneditor' which is targeted by the JavaScript code, and basic body styling.
```html
JSONEditor Example
```
--------------------------------
### JSONEditor Initialization and Configuration
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/15_selection_api.html
Demonstrates how to initialize a JSONEditor instance with various configuration options and event handlers. Includes setting modes, indentation, and handling selection changes.
```javascript
const container = document.getElementById('jsoneditor')
const options = {
mode: 'tree',
modes: ['code', 'form', 'text', 'tree', 'view', 'preview'],
// allowed modes
onChange: function () {
console.log('change')
},
onModeChange: function (mode) {
const treeMode = document.getElementById('treeModeSelection')
const textMode = document.getElementById('textModeSelection')
treeMode.style.display = textMode.style.display = 'none'
if (mode === 'code' || mode === 'text') {
textMode.style.display = 'inline'
} else {
treeMode.style.display = 'inline'
}
},
indentation: 4,
escapeUnicode: true,
onTextSelectionChange: function(start, end, text) {
const rangeEl = document.getElementById('textRange')
rangeEl.innerHTML = 'start: ' + JSON.stringify(start) + ', end: ' + JSON.stringify(end)
const textEl = document.getElementById('selectedText')
textEl.innerHTML = text
},
onSelectionChange: function(start, end) {
const nodesEl = document.getElementById('selectedNodes')
nodesEl.innerHTML = ''
if (start) {
nodesEl.innerHTML = ('start: ' + JSON.stringify(start))
if (end) {
nodesEl.innerHTML += (' end: ' + JSON.stringify(end))
}
}
}
}
const json = {
"array": [1, 2, [3,4,5]],
"boolean": true,
"htmlcode": '"',
"escaped_unicode": '\\u20b9',
"unicode": '\u20b9,\uD83D\uDCA9',
"return": '\n',
"null": null,
"number": 123,
"object": {"a": "b", "c": "d"},
"string": "Hello World",
"url": "http://jsoneditoronline.org"
}
window.editor = new JSONEditor(container, options, json)
console.log('json', json)
console.log('string', JSON.stringify(json))
```
--------------------------------
### Get JSON Data from Editor (JavaScript)
Source: https://github.com/josdejong/jsoneditor/blob/develop/docs/usage.md
Retrieve the current JSON data from the editor using the `get` method. This returns the data as a JavaScript object.
```javascript
var json = editor.get();
```
--------------------------------
### Initialize JSONEditor with Schema and Options
Source: https://github.com/josdejong/jsoneditor/blob/develop/test/test_popup_anchor.html
Demonstrates how to create and configure a JSONEditor instance. It includes defining a JSON schema, schema references, editor options, and the initial JSON data. The editor is then initialized and all its contents are expanded.
```javascript
const schema = {
"title": "Employee",
"description": "Object containing employee details",
"type": "object",
"properties": {
"firstName": {
"title": "First Name",
"description": "The given name.",
"examples": [
"John"
],
"type": "string"
},
"lastName": {
"title": "Last Name",
"description": "The family name.",
"examples": [
"Smith"
],
"type": "string"
},
"gender": {
"title": "Gender",
"enum": [
"male",
"female"
]
},
"availableToHire": {
"type": "boolean",
"default": false
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0,
"examples": [
28,
32
]
},
"job": {
"$ref": "job"
}
},
"required": [
"firstName",
"lastName"
]
};
const job = {
"title": "Job description",
"type": "object",
"required": [
"address"
],
"properties": {
"company": {
"type": "string",
"examples": [
"ACME",
"Dexter Industries"
]
},
"role": {
"description": "Job title.",
"type": "string",
"examples": [
"Human Resources Coordinator",
"Software Developer"
],
"default": "Software Developer"
},
"address": {
"type": "string"
},
"salary": {
"type": "number",
"minimum": 120,
"examples": [
100,
110,
120
]
}
}
};
const json = {
"firstName": "John",
"lastName": "Doe",
"gender": null,
"age": "28",
"availableToHire": true,
"favoriteColor": "red",
"job": {
"company": "freelance",
"role": "developer",
"salary": 100
}
};
const options = {
"schema": schema,
"schemaRefs": {
"job": job
},
"mode": "tree",
"modes": [
"code",
"text",
"tree",
"preview"
],
"popupAnchor": document.getElementById('anchor')
};
// create the editor
const container = document.getElementById('jsoneditor');
const editor = new JSONEditor(container, options, json);
editor.expandAll();
```
--------------------------------
### Initialize JSONEditor with Options and Data
Source: https://github.com/josdejong/jsoneditor/blob/develop/test/test_code_mode.html
Demonstrates initializing the JSONEditor library with a container element, configuration options, and sample JSON data. The options include setting the editor mode, defining allowed modes, specifying callbacks for errors and changes, and configuring indentation. It also generates a large dataset for demonstration purposes.
```javascript
var container, options, json, editor;
// Get the container element for the editor
container = document.getElementById('jsoneditor');
// Define editor options
options = {
mode: 'code', // Initial mode
modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // Allowed modes
onError: function (err) {
alert(err.toString()); // Error handler
},
onChange: function () {
console.log('change'); // Callback on any change
},
onChangeJSON: function (json) {
console.log('onChangeJSON', json); // Callback when JSON content changes
},
onChangeText: function (text) {
console.log('onChangeText', text); // Callback when text content changes
},
indentation: 4, // Number of spaces for indentation
escapeUnicode: true // Whether to escape unicode characters
};
// Generate sample JSON data
var json = [];
for (var i = 0; i < 10000; i++) {
var longitude = 4 + i / 10000;
var latitude = 51 + i / 10000;
json.push({
name: 'Item ' + i,
id: String(i),
index: i,
time: new Date().toISOString(),
location: {
latitude: longitude,
longitude: latitude,
coordinates: [longitude, latitude]
},
random: Math.random()
});
}
// Create a new JSONEditor instance
// The variable name 'editorTest' is used here as per the original text.
var editorTest = new JSONEditor(container, options, json);
// Log the size of the stringified JSON data
console.log('stringified size: ', Math.round(JSON.stringify(json).length / 1024 / 1024), 'MB');
```
--------------------------------
### Custom Ace Editor Usage Example
Source: https://github.com/josdejong/jsoneditor/blob/develop/HISTORY.md
Documentation and an example are provided on how to use a custom version of the Ace editor with JSONEditor. This was mentioned in version 5.5.11.
```APIDOC
Documentation:
Custom Ace Editor Integration
Description:
Provides guidance and examples on how to integrate a custom build or version of the Ace editor with JSONEditor, particularly for scenarios where the embedded Ace theme might not load correctly or custom configurations are needed.
Version Mentioned:
5.5.11
Related Issues:
#55
```
--------------------------------
### Example JSON Data for Employee
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/26_autocomplete_by_schema.html
An example JSON object representing employee details, conforming to the defined schema. This data is used to initialize the JSONEditor instance.
```javascript
const json = { firstName: "John", lastName: "Doe", gender: "male", age: 28, availableToHire: true, job: { company: "freelance", role: "developer", salary: 140, address: "Jerusalem" }, profession: { level: "senior", experience: 10 }, publications: [{ type: 'academic', journal: 'MIT today' }, { type: 'professional', journal: 'stack overflow' }] }
```
--------------------------------
### Initialize JSONEditor with Options
Source: https://github.com/josdejong/jsoneditor/blob/develop/test/test_destroy.html
Demonstrates how to initialize a JSONEditor instance within a container element. It includes common configuration options for modes, error handling, and indentation. Dependencies include the JSONEditor library and a target DOM element.
```javascript
var container, options, json, editor;
container = document.getElementById('jsoneditor');
options = {
mode: 'tree',
modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
onError: function (err) {
alert(err.toString());
},
onChange: function () {
console.log('change');
},
indentation: 4,
escapeUnicode: true
};
json = {
"array": [1, 2, [3,4,5]],
"boolean": true,
"htmlcode": '"',
"escaped_unicode": '\\u20b9',
"unicode": '\u20b9,\uD83D\uDCA9',
"return": '\n',
"null": null,
"number": 123,
"object": {"a": "b", "c": "d"},
"string": "Hello World",
"url": "http://jsoneditoronline.org"
};
editor = new JSONEditor(container, options, json);
console.log('json', json);
console.log('string', JSON.stringify(json));
```
--------------------------------
### JSONEditor Custom Validation Example
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/18_custom_validation.html
This JavaScript code snippet demonstrates how to implement custom validation logic for JSON data using the JSONEditor library. It defines rules for team members, including required properties, data types, team size, and age requirements, returning an array of validation errors.
```javascript
const json = { team: [ { name: 'Joe', age: 17 }, { name: 'Sarah', age: 13 }, { name: 'Jack' } ] }
const options = {
mode: 'tree',
modes: ['code', 'text', 'tree', 'preview'],
onValidate: function (json) {
// rules:
// - team, names, and ages must be filled in and be of correct type
// - a team must have 4 members
// - at lease one member of the team must be adult
const errors = []
if (json && Array.isArray(json.team)) {
// check whether each team member has name and age filled in correctly
json.team.forEach(function (member, index) {
if (typeof member !== 'object') {
errors.push({path: ['team', index], message: 'Member must be an object with properties "name" and "age"'})
}
if ('name' in member) {
if (typeof member.name !== 'string') {
errors.push({path: ['team', index, 'name'], message: 'Name must be a string'})
}
} else {
errors.push({path: ['team', index], message: 'Required property "name"" missing'})
}
if ('age' in member) {
if (typeof member.age !== 'number') {
errors.push({path: ['team', index, 'age'], message: 'Age must be a number'})
}
} else {
errors.push({path: ['team', index], message: 'Required property "age" missing'})
}
})
// check whether the team consists of exactly four members
if (json.team.length !== 4) {
errors.push({path: ['team'], message: 'A team must have 4 members'})
}
// check whether there is at least one adult member in the team
const adults = json.team.filter(function (member) {
return member ? member.age >= 18 : false
})
if (adults.length === 0) {
errors.push({path: ['team'], message: 'A team must have at least one adult person (age >= 18)'})
}
} else {
errors.push({path: [], message: 'Required property "team" missing or not an Array'})
}
return errors
}
}
// create the editor
const container = document.getElementById('jsoneditor')
const editor = new JSONEditor(container, options, json)
editor.expandAll()
```
--------------------------------
### Async Custom Validation with JSONEditor
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/19_custom_validation_async.html
This example demonstrates how to run asynchronous custom validation on a JSON object using the JSONEditor library. The `onValidate` callback is used to simulate server requests for validating data, returning results asynchronously. It includes a helper function `isExistingCustomer` that fakes a network request with a 500ms delay.
```javascript
const json = { customers: [
{name: 'Joe'},
{name: 'Sarah'},
{name: 'Harry'},
] }
const options = {
mode: 'tree',
modes: ['code', 'text', 'tree', 'preview'],
onValidate: function (json) {
// in this validation function we fake sending a request to a server
// to validate the existence of customers
if (json && Array.isArray(json.customers)) {
return Promise
.all(json.customers.map(function (customer, index) {
return isExistingCustomer(customer && customer.name).then(function (exists) {
if (!exists) {
return {
path: ['customers', index],
message: 'Customer ' + customer.name + ' doesn\'t exist in our database'
}
} else {
return null
}
})
}))
.then(function (errors) {
return errors.filter(function (error) {
return error != null
})
})
} else {
return null
}
}
}
// create the editor
const container = document.getElementById('jsoneditor')
const editor = new JSONEditor(container, options, json)
editor.expandAll()
// this function fakes a request (asynchronous) to a server to validate the existence of a customer
function isExistingCustomer (customerName) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
const customers = ['Joe', 'Harry', 'Megan']
const exists = customers.indexOf(customerName) !== -1
resolve(exists)
}, 500)
})
}
```
--------------------------------
### JSON Schema Validation with JSONEditor
Source: https://github.com/josdejong/jsoneditor/blob/develop/examples/07_json_schema_validation.html
Demonstrates JSON schema validation using the JSONEditor library. It defines a JSON schema for employee details, including properties like firstName, lastName, and age, along with sample JSON data and editor initialization options. The example highlights how to set up schema validation and cross-references.
```javascript
const schema = { "title": "Employee", "description": "Object containing employee details", "type": "object", "properties": { "firstName": { "title": "First Name", "description": "The given name.", "examples": [ "John" ], "type": "string" }, "lastName": { "title": "Last Name", "description": "The family name.", "examples": [ "Smith" ], "type": "string" }, "gender": { "title": "Gender", "enum": ["male", "female"] }, "availableToHire": { "type": "boolean", "default": false }, "age": { "description": "Age in years", "type": "integer", "minimum": 0, "examples": [28, 32] }, "job": { "$ref": "job" } }, "required": ["firstName", "lastName"] }
const job = { "title": "Job description", "type": "object", "required": ["address"], "properties": { "company": { "type": "string", "examples": [ "ACME", "Dexter Industries" ] }, "role": { "description": "Job title.", "type": "string", "examples": [ "Human Resources Coordinator", "Software Developer" ], "default": "Software Developer" }, "address": { "type": "string" }, "salary": { "type": "number", "minimum": 120, "examples": [100, 110, 120] } } }
const json = { firstName: 'John', lastName: 'Doe', gender: null, age: "28", availableToHire: true, job: { company: 'freelance', role: 'developer', salary: 100 } }
const options = { schema: schema, schemaRefs: {"job": job}, mode: 'tree', modes: ['code', 'text', 'tree', 'preview'] }
// create the editor
const container = document.getElementById('jsoneditor')
const editor = new JSONEditor(container, options, json)
```