svelte-jsoneditor
svelte-jsoneditor
A web-based tool to view, edit, format, transform, and validate JSON.
Try it out:
https://jsoneditoronline.org
The library is written with Svelte, but can be used in plain JavaScript too and in any framework (SolidJS, React, Vue, Angular, etc).
Features
- View and edit JSON
- Has a low level text editor and high level tree view and table view
- Format (beautify) and compact JSON
- Sort, query, filter, and transform JSON
- Repair JSON
- JSON schema validation and pluggable custom validation
- Color highlighting, undo/redo, search and replace
- Utilities like a color picker and timestamp tag
- Handles large JSON documents up to 512 MB
Install
For usage in a Svelte project:
npm install svelte-jsoneditor
For usage in vanilla JavaScript or frameworks like SolidJS, React, Vue, Angular, etc:
npm install vanilla-jsoneditor
Use
Examples
- Svelte examples: /src/routes/examples
- Plain JavaScript examples: /examples/browser
- React example: https://codesandbox.io/s/svelte-jsoneditor-react-59wxz
- Vue example: https://codesandbox.io/s/svelte-jsoneditor-vue-toln3w
Svelte usage
Create a JSONEditor with two-way binding bind:json
:
<script> import { JSONEditor } from 'svelte-jsoneditor' let content = { text: undefined, // can be used to pass a stringified JSON document instead json: { array: [1, 2, 3], boolean: true, color: '#82b92c', null: null, number: 123, object: { a: 'b', c: 'd' }, string: 'Hello World' } } </script> <div> <JSONEditor bind:content /> </div>
Or one-way binding:
<script> import { JSONEditor } from 'svelte-jsoneditor' let content = { text: undefined, // can be used to pass a stringified JSON document instead json: { greeting: 'Hello World' } } function handleChange(updatedContent, previousContent, { contentErrors, patchResult }) { // content is an object { json: JSONValue } | { text: string } console.log('onChange: ', { updatedContent, previousContent, contentErrors, patchResult }) content = updatedContent } </script> <div> <JSONEditor {content} onChange="{handleChange}" /> </div>
Standalone bundle (use in React, Vue, Angular, plain JavaScript, …)
The library provides a standalone bundle of the editor via the npm library vanilla-jsoneditor
(instead of svelte-jsoneditor
) which can be used in any browser environment and framework. In a framework like React, Vue, or Angular, you’ll need to write some wrapper code around the class interface.
Browser example loading the ES module:
<!DOCTYPE html> <html lang="en"> <head> <title>JSONEditor</title> </head> <body> <div id="jsoneditor"></div> <script type="module"> import { JSONEditor } from 'vanilla-jsoneditor' let content = { text: undefined, json: { greeting: 'Hello World' } } const editor = new JSONEditor({ target: document.getElementById('jsoneditor'), props: { content, onChange: (updatedContent, previousContent, { contentErrors, patchResult }) => { // content is an object { json: JSONValue } | { text: string } console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult }) content = updatedContent } } }) // use methods get, set, update, and onChange to get data in or out of the editor. // Use updateProps to update properties. </script> </body> </html>
Wrapper libraries for specific frameworks
To make it easier to use the library in your framework of choice, you can use a wrapper library:
-
Vue:
- json-editor-vue
- vue3-ts-jsoneditor
API
constructor
Svelte component:
<script> import { JSONEditor } from 'svelte-jsoneditor' let content = { text: '[1,2,3]' } </script> <div> <JSONEditor {content} /> </div>
JavasScript class:
import { JSONEditor } from 'vanilla-jsoneditor' const content = { text: '[1,2,3]' } const editor = new JSONEditor({ target: document.getElementById('jsoneditor'), props: { content, onChange: (updatedContent, previousContent, { contentErrors, patchResult }) => { // content is an object { json: JSONValue } | { text: string } console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult }) } } })
properties
-
content: Content
Pass the JSON contents to be rendered in the JSONEditor.Content
is an object containing a propertyjson
(a parsed JSON document) ortext
(a stringified JSON document). Only one of the two properties must be defined. You can pass both content types to the editor independent of in what mode it is. -
mode: 'tree' | 'text' | 'table'
. Open the editor in'tree'
mode (default),'table'
mode, or'text'
mode (formerly:code
mode). -
mainMenuBar: boolean
Show the main menu bar. Default value istrue
. -
navigationBar: boolean
Show the navigation bar with, where you can see the selected path and navigate through your document from there. Default value istrue
. -
statusBar: boolean
Show a status bar at the bottom of the'text'
editor, showing information about the cursor location and selected contents. Default value istrue
. -
readOnly: boolean
Open the editor in read-only mode: no changes can be made, non-relevant buttons are hidden from the menu, and the context menu is not enabled. Default value isfalse
. -
indentation: number | string
Number of spaces use for indentation when stringifying JSON, or a string to be used as indentation like't'
to use a tab as indentation, or' '
to use 4 spaces (which is equivalent to configuringindentation: 4
). See also propertytabSize
. -
tabSize: number
When indentation is configured as a tab character (indentation: 't'
),tabSize
configures how large a tab character is rendered. Default value is4
. Only applicable totext
mode. -
escapeControlCharacters: boolean
. False by default. Whentrue
, control characters like newline and tab are rendered as escaped charactersn
andt
. Only applicable for'tree'
mode, in'text'
mode control characters are always escaped. -
escapeUnicodeCharacters: boolean
. False by default. Whentrue
, unicode characters like ☎ and 😀 are rendered escaped likeu260e
andud83dude00
. -
flattenColumns: boolean
. True by default. Only applicable to'table'
mode. Whentrue
, nested object properties will be displayed each in their own column, with the nested path as column name. Whenfalse
, nested objects will be rendered inline, and double-clicking them will open them in a popup. -
validator: function (json: JSONValue): ValidationError[]
. Validate the JSON document.
For example use the built-in JSON Schema validator powered by Ajv:import { createAjvValidator } from 'svelte-jsoneditor'
const validator = createAjvValidator({ schema, schemaDefinitions })
-
parser: JSON = JSON
. Configure a custom JSON parser, likelossless-json
. By default, the nativeJSON
parser of JavaScript is used. TheJSON
interface is an object with aparse
andstringify
function. For example:<script> import { JSONEditor } from 'svelte-jsoneditor' import { parse, stringify } from 'lossless-json'
const LosslessJSONParser = { parse, stringify }
let content = { text: ‘[1,2,3]’ } </script>
<div> <JSONEditor {content} parser="{LosslessJSONParser}" /> </div>
-
validationParser: JSONParser = JSON
. Only applicable when avalidator
is provided. This is the same asparser
, except that this parser is used to parse the data before sending it to the validator. Configure a custom JSON parser that is used to parse JSON before passing it to thevalidator
. By default, the built-inJSON
parser is used. When passing a customvalidationParser
, make sure the output of the parser is supported by the configuredvalidator
. So, when thevalidationParser
can outputbigint
numbers or other numeric types, thevalidator
must also support that. In tree mode, whenparser
is not equal tovalidationParser
, the JSON document will be converted before it is passed to thevalidator
viavalidationParser.parse(parser.stringify(json))
. -
pathParser: JSONPathParser
. An optional object with a parse and stringify method to parse and stringify aJSONPath
, which is an array with property names. ThepathParser
is used in the path editor in the navigation bar, which is opened by clicking the edit button on the right side of the navigation bar. ThepathParser.parse
function is allowed to throw an Error when the input is invalid. By default, a JSON Path notation is used, which looks like$.data[2].nested.property
. Alternatively, it is possible to use for example a JSON Pointer notation like/data/2/nested/property
or something custom-made. Related helper functions:parseJSONPath
andstringifyJSONPath
,parseJSONPointer
andcompileJSONPointer
. -
onError(err: Error)
.
Callback fired when an error occurs. Default implementation is to log an error in the console and show a simple alert message to the user. -
onChange(content: Content, previousContent: Content, changeStatus: { contentErrors: ContentErrors, patchResult: JSONPatchResult | null })
. The callback which is invoked on every change of the contents, both changes made by a user and programmatic changes made via methods like.set()
,.update()
, or.patch()
.
The returnedcontent
is sometimes of type{ json }
, and sometimes of type{ text }
. Which of the two is returned depends on the mode of the editor, the change that is applied, and the state of the document (valid, invalid, empty). Please be aware that{ text }
can contain invalid JSON: whilst typing intext
mode, a JSON document will be temporarily invalid, like when the user is typing a new string. The parameterpatchResult
is only returned on changes that can be represented as a JSON Patch document, and for example not when freely typing intext
mode. -
onChangeMode(mode: 'tree' | 'text' | 'table')
. Invoked when the mode is changed. -
onClassName(path: Path, value: any): string | undefined
.
Add a custom class name to specific…