Gathering detailed insights and metrics for svelte-jsoneditor
Gathering detailed insights and metrics for svelte-jsoneditor
Gathering detailed insights and metrics for svelte-jsoneditor
Gathering detailed insights and metrics for svelte-jsoneditor
vanilla-jsoneditor
A web-based tool to view, edit, format, transform, and validate JSON
vue3-ts-jsoneditor
[![npm version](https://badge.fury.io/js/vue3-ts-jsoneditor.svg)](https://badge.fury.io/js/vue3-ts-jsoneditor) ![NPM](https://img.shields.io/npm/l/vue3-ts-jsoneditor) ![npm](https://img.shields.io/npm/dm/vue3-ts-jsoneditor) <br> [![npm](https://img.shield
jsoneditor
A web-based tool to view, edit, format, and validate JSON
jsoneditor-standalone
This is a wrapper for jsoneditor package, it can be run offline without any dependencies and privacy concerns.
npm install svelte-jsoneditor
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
937 Stars
1,203 Commits
112 Forks
9 Watching
2 Branches
19 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
TypeScript (54.19%)
Svelte (36.26%)
SCSS (6.38%)
HTML (1.36%)
JavaScript (1.24%)
CSS (0.57%)
Cumulative downloads
Total Downloads
Last day
-18.5%
1,242
Compared to previous day
Last week
-8.2%
6,249
Compared to previous week
Last month
11.9%
30,722
Compared to previous month
Last year
83.7%
280,059
Compared to previous year
28
1
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.). It requires a browser from March 2022 or newer.
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
Create a JSONEditor with two-way binding bind:json
:
1<script> 2 import { JSONEditor } from 'svelte-jsoneditor' 3 4 let content = { 5 text: undefined, // can be used to pass a stringified JSON document instead 6 json: { 7 array: [1, 2, 3], 8 boolean: true, 9 color: '#82b92c', 10 null: null, 11 number: 123, 12 object: { a: 'b', c: 'd' }, 13 string: 'Hello World' 14 } 15 } 16</script> 17 18<div> 19 <JSONEditor bind:content /> 20</div>
Or one-way binding:
1<script> 2 import { JSONEditor } from 'svelte-jsoneditor' 3 4 let content = { 5 text: undefined, // can be used to pass a stringified JSON document instead 6 json: { 7 greeting: 'Hello World' 8 } 9 } 10 11 function handleChange(updatedContent, previousContent, { contentErrors, patchResult }) { 12 // content is an object { json: unknown } | { text: string } 13 console.log('onChange: ', { updatedContent, previousContent, contentErrors, patchResult }) 14 content = updatedContent 15 } 16</script> 17 18<div> 19 <JSONEditor {content} onChange="{handleChange}" /> 20</div>
The library provides a vanilla 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.
If you have a setup for your project with a bundler (like Vite, Rollup, or Webpack), it is best to use the default ES import:
1// for use in a React, Vue, or Angular project 2import { JSONEditor } from 'vanilla-jsoneditor'
If you want to use the library straight in the browser, use the provided standalone ES bundle:
1// for use directly in the browser 2import { createJSONEditor } from 'vanilla-jsoneditor/standalone.js'
The standalone bundle contains all dependencies of vanilla-jsoneditor
, for example lodash-es
and Ajv
. If you use some of these dependencies in your project too, it means that they will be bundled twice in your web application, leading to a needlessly large application size. In general, it is preferable to use the default import { createJSONEditor } from 'vanilla-jsoneditor'
instead of the standalone bundle so dependencies can be reused.
Browser example loading the standalone ES module:
1<!doctype html> 2<html lang="en"> 3 <head> 4 <title>JSONEditor</title> 5 </head> 6 <body> 7 <div id="jsoneditor"></div> 8 9 <script type="module"> 10 import { createJSONEditor } from 'vanilla-jsoneditor/standalone.js' 11 12 // Or use it through a CDN (not recommended for use in production): 13 // import { createJSONEditor } from 'https://unpkg.com/vanilla-jsoneditor/standalone.js' 14 // import { createJSONEditor } from 'https://cdn.jsdelivr.net/npm/vanilla-jsoneditor/standalone.js' 15 16 let content = { 17 text: undefined, 18 json: { 19 greeting: 'Hello World' 20 } 21 } 22 23 const editor = createJSONEditor({ 24 target: document.getElementById('jsoneditor'), 25 props: { 26 content, 27 onChange: (updatedContent, previousContent, { contentErrors, patchResult }) => { 28 // content is an object { json: unknown } | { text: string } 29 console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult }) 30 content = updatedContent 31 } 32 } 33 }) 34 35 // use methods get, set, update, and onChange to get data in or out of the editor. 36 // Use updateProps to update properties. 37 </script> 38 </body> 39</html>
To make it easier to use the library in your framework of choice, you can use a wrapper library:
Svelte component:
1<script> 2 import { JSONEditor } from 'svelte-jsoneditor' 3 4 let content = { text: '[1,2,3]' } 5</script> 6 7<div> 8 <JSONEditor {content} /> 9</div>
JavasScript class:
1import { createJSONEditor } from 'vanilla-jsoneditor' // or 'vanilla-jsoneditor/standalone.js' 2 3const content = { text: '[1,2,3]' } 4 5const editor = createJSONEditor({ 6 target: document.getElementById('jsoneditor'), 7 props: { 8 content, 9 onChange: (updatedContent, previousContent, { contentErrors, patchResult }) => { 10 // content is an object { json: unknown } | { text: string } 11 console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult }) 12 } 13 } 14})
Properties such as content
and mode
are either passed as attributes to the Svelte component, like <JSONEditor {content} {mode} />
, or via the props
in case of the vanilla JS factory function: createJSONEditor({ target, props: { content, mode }
.
1content: Content
Pass the JSON contents to be rendered in the JSONEditor. Content
is an object containing a property json
(a parsed JSON document) or text
(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. You can use two-way binding via bind:content
.
IMPORTANT: only make immutable changes to
content
. Mutable changes will mess up history and rendered contents. See section Immutability.
1selection: JSONEditorSelection | undefined
The current selected contents. You can use two-way binding using bind:selection
. The tree
mode supports MultiSelection
, KeySelection
, EditKeySelection
, ValueSelection
, EditValueSelection
, InsideSelection
, or AfterSelection
. The table
mode supports ValueSelection
, and text
mode supports TextSelection.
.
1mode: 'tree' | 'text' | 'table'
Open the editor in 'tree'
mode (default), 'table'
mode, or 'text'
mode (formerly: code
mode).
1mainMenuBar: boolean
Show the main menu bar. Default value is true
.
1navigationBar: boolean
Show the navigation bar with, where you can see the selected path and navigate through your document from there. Default value is true
.
1statusBar: boolean
Show a status bar at the bottom of the 'text'
editor, showing information about the cursor location and selected contents. Default value is true
.
1askToFormat: boolean
When true
(default), the user will be asked whether he/she wants to format the JSON document when a compact document is loaded or pasted in 'text'
mode. Only applicable to 'text'
mode.
1readOnly: 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 is false
.
1indentation: 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 configuring indentation: 4
). See also property tabSize
.
1tabSize: number
When indentation is configured as a tab character (indentation: '\t'
), tabSize
configures how large a tab character is rendered. Default value is 4
. Only applicable to text
mode.
1escapeControlCharacters: boolean
False by default. When true
, control characters like newline and tab are rendered as escaped characters \n
and \t
. Only applicable for 'tree'
mode, in 'text'
mode control characters are always escaped.
1escapeUnicodeCharacters: boolean
False by default. When true
, unicode characters like ☎ and 😀 are rendered escaped like \u260e
and \ud83d\ude00
.
1flattenColumns: boolean
True by default. Only applicable to 'table'
mode. When true
, nested object properties will be displayed each in their own column, with the nested path as column name. When false
, nested objects will be rendered inline, and double-clicking them will open them in a popup.
1validator: function (json: unknown): ValidationError[]
Validate the JSON document. For example use the built-in JSON Schema validator powered by Ajv:
1import { createAjvValidator } from 'svelte-jsoneditor' 2 3const validator = createAjvValidator({ schema, schemaDefinitions })
1parser: JSON = JSON
Configure a custom JSON parser, like lossless-json
. By default, the native JSON
parser of JavaScript is used. The JSON
interface is an object with a parse
and stringify
function. For example:
1<script> 2 import { JSONEditor } from 'svelte-jsoneditor' 3 import { parse, stringify } from 'lossless-json' 4 5 const LosslessJSONParser = { parse, stringify } 6 7 let content = { text: '[1,2,3]' } 8</script> 9 10<div> 11 <JSONEditor {content} parser="{LosslessJSONParser}" /> 12</div>
1validationParser: JSONParser = JSON
Only applicable when a validator
is provided. This is the same as parser
, 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 the validator
. By default, the built-in JSON
parser is used. When passing a custom validationParser
, make sure the output of the parser is supported by the configured validator
. So, when the validationParser
can output bigint
numbers or other numeric types, the validator
must also support that. In tree mode, when parser
is not equal to validationParser
, the JSON document will be converted before it is passed to the validator
via validationParser.parse(parser.stringify(json))
.
1pathParser: JSONPathParser
An optional object with a parse and stringify method to parse and stringify a JSONPath
, which is an array with property names. The pathParser
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. The pathParser.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
and stringifyJSONPath
, parseJSONPointer
and compileJSONPointer
.
1onError(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.
1onChange(content: Content, previousContent: Content, changeStatus: { contentErrors: ContentErrors | undefined, patchResult: JSONPatchResult | undefined })
The callback which is invoked on every change of the contents made by the user from within the editor. It will not trigger on changes that are applied programmatically via methods like .set()
, .update()
, or .patch()
.
The returned content
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 in text
mode, a JSON document will be temporarily invalid, like when the user is typing a new string. The parameter patchResult
is only returned on changes that can be represented as a JSON Patch document, and for example not when freely typing in text
mode.
1onChangeMode(mode: 'tree' | 'text' | 'table')
Invoked when the mode is changed.
1onClassName(path: JSONPath, value: any): string | undefined
Add a custom class name to specific nodes, based on their path and/or value. Note that in the custom class, you can override CSS variables like --jse-contents-background-color
to change the styling of a node, like the background color. Relevant variables are:
1--jse-contents-background-color 2--jse-selection-background-color 3--jse-selection-background-inactive-color 4--jse-hover-background-color 5--jse-context-menu-pointer-hover-background 6--jse-context-menu-pointer-background 7--jse-context-menu-pointer-background-highlight 8--jse-collapsed-items-background-color 9--jse-collapsed-items-selected-background-color
To adjust the text color of keys or values, the color of the classes .jse-key
and .jse-value
can be overwritten.
1onRenderValue(props: RenderValueProps) : RenderValueComponentDescription[]
Customize rendering of the values. By default, renderValue
is used, which renders a value as an editable div and depending on the value can also render a boolean toggle, a color picker, and a timestamp tag. Multiple components can be rendered alongside each other, like the boolean toggle and color picker being rendered left from the editable div. In order to disable for example the built-in color picker or timestamp tag, you can look up the source code of renderValue
, copy it, and then remove the components that you do not want from the function. Built in value renderer components: EditableValue
, ReadonlyValue
, BooleanToggle
, ColorPicker
, TimestampTag
, EnumValue
.
For JSON Schema enums, there is a ready-made value renderer renderJSONSchemaEnum
which renders enums using the EnumValue
component. This can be used like:
1import { renderJSONSchemaEnum, renderValue } from 'svelte-jsoneditor'
2
3function onRenderValue(props) {
4 // use the enum renderer, and fallback on the default renderer
5 return renderJSONSchemaEnum(props, schema, schemaDefinitions) || renderValue(props)
6}
The callback onRenderValue
must return an array with one or multiple renderers. Each renderer can be either a Svelte component or a Svelte action:
1interface SvelteComponentRenderer { 2 component: typeof SvelteComponent<RenderValuePropsOptional> 3 props: Record<string, unknown> 4} 5 6interface SvelteActionRenderer { 7 action: Action // Svelte Action 8 props: Record<string, unknown> 9}
The SvelteComponentRenderer
interface can be used to provide Svelte components like the EnumValue
component mentioned above. The SvelteActionRenderer
expects a Svelte Action as action
property. Since this interface is a plain JavaScript interface, this allows to create custom components in a vanilla JS environment. Basically it is a function that gets a DOM node passed, and needs to return an object with update
and destroy
functions:
1const myRendererAction = { 2 action: (node) => { 3 // attach something to the HTML DOM node 4 return { 5 update: (node) => { 6 // update the DOM 7 }, 8 destroy: () => { 9 // cleanup the DOM 10 } 11 } 12 } 13}
1onRenderMenu(items: MenuItem[], context: { mode: 'tree' | 'text' | 'table', modal: boolean, readOnly: boolean }) : MenuItem[] | undefined
Callback which can be used to make changes to the menu items. New items can be added, or existing items can be removed or reorganized. When the function returns undefined
, the original items
will be applied.
Using the context values mode
, modal
, and readOnly
, different actions can be taken depending on the mode of the editor and whether the editor is rendered inside a modal or not, or depending on whether it is read-only.
A menu item MenuItem
can be one of the following types:
Button:
1interface MenuButton { 2 type: 'button' 3 onClick: () => void 4 icon?: IconDefinition 5 text?: string 6 title?: string 7 className?: string 8 disabled?: boolean 9}
Separator (gray vertical line between a group of items):
1interface MenuSeparator { 2 type: 'separator' 3}
Space (fills up empty space):
1interface MenuSpace { 2 type: 'space' 3}
1onRenderContextMenu(items: ContextMenuItem[], context: { mode: 'tree' | 'text' | 'table', modal: boolean, readOnly: boolean, selection: JSONEditorSelection | undefined }) : ContextMenuItem[] | false | undefined
Callback which can be used to make changes to the context menu items. New items can be added, or existing items can be removed or reorganized. When the function returns undefined
, the original items
will be applied and the context menu will be displayed when readOnly
is false
. When the function returns false
, the context menu will never be displayed. The callback is triggered too when the editor is readOnly
, and in most cases you want to return false
then.
Using the context values mode
, modal
, readOnly
and selection
, different actions can be taken depending on the mode of the editor, whether the editor is rendered inside a modal or not, whether the editor is read-only or not, and depending on the path of selection.
A menu item ContextMenuItem
can be one of the following types:
Button:
1interface MenuButton { 2 type: 'button' 3 onClick: () => void 4 icon?: IconDefinition 5 text?: string 6 title?: string 7 className?: string 8 disabled?: boolean 9}
Dropdown button:
1interface MenuDropDownButton { 2 type: 'dropdown-button' 3 main: MenuButton 4 width?: string 5 items: MenuButton[] 6}
Separator (gray line between a group of items):
1interface MenuSeparator { 2 type: 'separator' 3}
Menu row and column:
1interface MenuLabel { 2 type: 'label' 3 text: string 4} 5 6interface ContextMenuColumn { 7 type: 'column' 8 items: Array<MenuButton | MenuDropDownButton | MenuLabel | MenuSeparator> 9} 10 11interface ContextMenuRow { 12 type: 'row' 13 items: Array<MenuButton | MenuDropDownButton | ContextMenuColumn> 14}
1onSelect: (selection: JSONEditorSelection | undefined) => void
Callback invoked when the selection is changed. When the selection is removed, the callback is invoked with undefined
as argument. In text
mode, a TextSelection
will be fired. In tree
and table
mode, a JSONSelection
will be fired (which can be MultiSelection
, KeySelection
, EditKeySelection
, ValueSelection
, EditValueSelection
, InsideSelection
, or AfterSelection
). Use typeguards like isTextSelection
and isValueSelection
to check what type the selection has.
1queryLanguages: QueryLanguage[]
Configure one or multiple query language that can be used in the Transform modal. The library comes with the following languages included:
The languages can be loaded as follows:
1import { 2 jsonQueryLanguage, 3 jmespathQueryLanguage, 4 jsonpathQueryLanguage, 5 lodashQueryLanguage, 6 javascriptQueryLanguage 7} from 'svelte-jsoneditor' 8 9const allQueryLanguages = [ 10 jsonQueryLanguage, 11 jmespathQueryLanguage, 12 jsonpathQueryLanguage, 13 lodashQueryLanguage, 14 javascriptQueryLanguage 15]
By default, only jsonQueryLanguage
is loaded in the editor.
Note that both lodashQueryLanguage
and javascriptQueryLanguage
can execute arbitrary JavaScript code and use new Function(...)
to execute the code. Therefore, they are not suitable in general to store or share queries because of the security risks. In some environments, trying to use them will result in CSP (Content Security Policy) errors depending on the security policy.
1queryLanguageId: string
The id
of the currently selected query language.
1onChangeQueryLanguage: (queryLanguageId: string) => void
Callback function invoked when the user changes the selected query language in the TransformModal via the configuration button top right.
onFocus()
callback fired when the editor got focus.onBlur()
callback fired when the editor lost focus.Methods can be called on a JSONEditor instance. In Svelte, you can create a reference and call a method like:
1<script> 2 let editor 3 4 function logContents() { 5 const content = editor.get() // using a method 6 console.log(content) 7 } 8</script> 9 10<JSONEditor bind:this={editor} />
In the vanilla editor, a factory function is used to create an editor instance:
1const editor = createJSONEditor({ ... }) 2 3function logContents() { 4 const content = editor.get() // using a method 5 console.log(content) 6}
Note that most methods are asynchronous and will resolve after the editor is re-rendered (on the next tick
).
1JSONEditor.prototype.get(): Content
Get the current JSON document.
IMPORTANT: do not mutate the received
content
, that will mess up history and rendered contents. See section Immutability.
1JSONEditor.prototype.set(content: Content): Promise<void>
Replace the current content. Will reset the state of the editor. See also method update(content)
.
1JSONEditor.prototype.update(content: Content): Promise<void>
Update the loaded content, keeping the state of the editor (like expanded objects). You can also call editor.updateProps({ content })
. See also method set(content)
.
IMPORTANT: only apply immutable changes to
content
. Mutable changes will mess up history and rendered contents. See section Immutability.
1JSONEditor.prototype.patch(operations: JSONPatchDocument) : Promise<JSONPatchResult>
Apply a JSON patch document to update the contents of the JSON document. A JSON patch document is a list with JSON Patch operations.
IMPORTANT: only apply immutable changes to the contents. Mutable changes will mess up history and rendered contents. See section Immutability.
1JSONEditor.prototype.updateProps(props: Object): Promise<void>
Tpdate some or all of the properties. Updated content
can be passed too; this is equivalent to calling update(content)
. Example:
1editor.updateProps({ 2 readOnly: true 3})
1JSONEditor.prototype.expand(path: JSONPath, callback?: (relativePath: JSONPath) => boolean = expandSelf): Promise<void>
Expand or collapse paths in the editor. All nodes along the provided path
will be expanded and become visible (rendered). So for example collapsed sections of an array will be expanded. Using the optional callback
, the node itself and some or all of its nested child nodes can be expanded too. The callback
function only iterates over the visible sections of an array and not over any of the collapsed sections. By default, the first 100 items of an array are visible and rendered.
Examples:
editor.expand([], () => true)
expand alleditor.expand([], relativePath => relativePath.length < 2)
expand all paths up to 2 levels deepeditor.expand(['array', '204'])
expand the root object, the array in this object, and the 204th item in the array.editor.expand(['array', '204'], () => false)
expand the root object, the array in this object, but not the 204th item itself.editor.expand(['array', '204'], relativePath => relativePath.length < 2)
expand the root object, the array in this object, and expand the 204th array item and all of its child's up to a depth of max 2 levels.The library exports a couple of utility functions for commonly used callback
functions:
expandAll
: recursively expand all nested objects and arrays.expandNone
: expand nothing, also not the root object or array.expandSelf
: expand the root array or object. This is the default for the callback
parameter.expandMinimal
: expand the root array or object, and in case of an array, expand the first array item.1JSONEditor.prototype.collapse(path: JSONPath, recursive?: boolean = false): Promise<void>
Collapse a path in the editor. When recursive
is true
, all nested objects and arrays will be collapsed too. The default value of recursive
is false
.
1JSONEditor.prototype.transform({ id?: string, rootPath?: [], onTransform: ({ operations: JSONPatchDocument, json: unknown, transformedJson: unknown }) => void, onClose: () => void })
Programmatically trigger clicking of the transform button in the main menu, opening the transform model. If a callback onTransform
is provided, it will replace the build-in logic to apply a transform, allowing you to process the transform operations in an alternative way. If provided, onClose
callback will trigger when the transform modal closes, both after the user clicked apply or cancel. If an id
is provided, the transform modal will load the previous status of this id
instead of the status of the editors transform modal.
1JSONEditor.prototype.scrollTo(path: JSONPath): Promise<void>
Scroll the editor vertically such that the specified path comes into view. Only applicable to modes tree
and table
. The path will be expanded when needed. The returned Promise is resolved after scrolling is finished.
1JSONEditor.prototype.findElement(path: JSONPath)
Find the DOM element of a given path. Returns null
when not found.
1JSONEditor.prototype.acceptAutoRepair(): Promise<Content>
In tree mode, invalid JSON is automatically repaired when loaded. When the repair was successful, the repaired contents are rendered but not yet applied to the document itself until the user clicks "Ok" or starts editing the data. Instead of accepting the repair, the user can also click "Repair manually instead". Invoking .acceptAutoRepair()
will programmatically accept the repair. This will trigger an update, and the method itself also returns the updated contents. In case of text
mode or when the editor is not in an "accept auto repair" status, nothing will happen, and the contents will be returned as is.
1JSONEditor.prototype.refresh(): Promise<void>
Refresh rendering of the contents, for example after changing the font size. This is only available in text
mode.
1JSONEditor.prototype.validate() : ContentErrors | undefined
Get all current parse errors and validation errors.
1JSONEditor.prototype.select(newSelection: JSONEditorSelection | undefined)
Change the current selection. See also option selection
.
1JSONEditor.prototype.focus(): Promise<void>
Give the editor focus.
1JSONEditor.prototype.destroy(): Promise<void>
Destroy the editor, remove it from the DOM.
The library exports a set of utility functions. The exact definitions of those functions can be found in the TypeScript d
renderValue
renderJSONSchemaEnum
BooleanToggle
ColorPicker
EditableValue
EnumValue
ReadonlyValue
TimestampTag
getValueClass
keyComboFromEvent
createAjvValidator
jsonQueryLanguage
jmespathQueryLanguage
lodashQueryLanguage
javascriptQueryLanguage
isContent
isTextContent
isJSONContent
isLargeContent
toTextContent
toJSONContent
estimateSerializedSize
expandAll
expandMinimal
expandNone
expandSelf
isValueSelection
isKeySelection
isInsideSelection
isAfterSelection
isMultiSelection
,isEditingSelection
createValueSelection
createEditValueSelection
createKeySelection
createEditKeySelection
createInsideSelection
,createAfterSelection
createMultiSelection
getFocusPath
getAnchorPath
getStartPath
getEndPath
getSelectionPaths
isEqualParser
parseJSONPath
stringifyJSONPath
resizeObserver
onEscape
valueType
stringConvert
isObject
isObjectOrArray
isBoolean
isTimestamp
isColor
isUrl
isContentParseError
isContentValidationErrors
immutable-json-patch
and use its functions:
immutableJSONPatch
revertJSONPatch
parseJSONPointer
parsePath
parseFrom
compileJSONPointer
compileJSONPointerProp
getIn
setIn
updateIn
insertAt
existsIn
deleteIn
The TypeScript types (like Content
, JSONSelection
, and JSONPatchOperation
) are defined in the following source file:
https://github.com/josdejong/svelte-jsoneditor/blob/main/src/lib/types.ts
The editor can be styled using the available CSS variables. A full list with all variables can be found here:
https://github.com/josdejong/svelte-jsoneditor/blob/main/src/lib/themes/defaults.scss
For example, to change the default blue theme color to anthracite:
1<script> 2 import { JSONEditor } from 'svelte-jsoneditor' 3 4 let content = { 5 text: undefined, // can be used to pass a stringified JSON document instead 6 json: { 7 string: 'Hello custom theme color :)' 8 } 9 } 10</script> 11 12<div class="my-json-editor"> 13 <JSONEditor bind:content /> 14</div> 15 16<style> 17 .my-json-editor { 18 /* define a custom theme color */ 19 --jse-theme-color: #383e42; 20 --jse-theme-color-highlight: #687177; 21 } 22</style>
The editor comes with a built-in dark theme. To use this theme:
themes/jse-theme-dark.css
jse-theme-dark
of the dark theme to the HTML container element where the editor is loaded.It is possible to load styling of multiple themes, and toggle them by changing the class name (like jse-theme-dark
) attached to the HTML container element.
Full Svelte example:
1<script> 2 import { JSONEditor } from 'svelte-jsoneditor' 3 4 let content = { 5 text: undefined, // can be used to pass a stringified JSON document instead 6 json: { 7 string: 'Hello dark theme :)' 8 } 9 } 10</script> 11 12<!-- use a theme by adding its name to the container class --> 13<div class="my-json-editor jse-theme-dark"> 14 <JSONEditor bind:content /> 15</div> 16 17<style> 18 /* load one or multiple themes */ 19 @import 'svelte-jsoneditor/themes/jse-theme-dark.css'; 20</style>
When updating CSS variables dynamically, it is necessary to refresh the via editorRef.refresh()
to update the font-size of the line numbers in the gutter and update the colors of the indentation markers in text
mode:
1<script> 2 let editorRef 3 4 function refresh() { 5 editorRef?.refresh() 6 } 7</script> 8<JSONEditor bind:this="{editorRef}" ... />
It is important that the content
of the editor is only updated in an immutable way. Mutating the content
will break the history (undo/redo), and will not always immediately update the user interface according to the changes.
The reasons for requiring immutable changes are:
Other advantages of an immutable way of working are that it makes the data that you work with much more predictive and less error-prone. You can learn more about immutability by searching for articles or videos about the subject, such as this video or this article. Immutability is not always the best choice, but in the case of this JSON Editor we're dealing with large and deeply nested data structures, in which we typically make only small changes like updating a single nested value. An immutable approach really shines here, enabling svelte-jsoneditor
to smoothly render and edit JSON documents up to 512 MB.
Here is an example of a mutable change:
1// mutable change (NOT SUPPORTED!)
2function updateDate() {
3 const lastEdited = new Date().toISOString()
4 const content = toJsonContent(myJsonEditor.get())
5 content.json.lastEdited = lastEdited // <- this is a mutable change
6 myJsonEditor.update(content)
7 // ERROR: The UI will not update immediately but only update after changing something
8 // inside the editor like the selection. And most importantly, history is broken now,
9 // because the original document is mutated. You cannot undo this action.
10}
Instead, you can apply the same change in an immutable way. There are various options for that:
1// immutable change using a libary like "mutative" or "immer" (efficient and easy to work with)
2import { create } from 'mutative'
3function updateDate1() {
4 const content = toJsonContent(myJsonEditor.get())
5 const updatedContent = create(content, (draft) => {
6 draft.json.lastEdited = new Date().toISOString()
7 })
8 myJsonEditor.update(updatedContent)
9}
10
11// immutable change using "immutable-json-patch"
12import { setIn } from 'immutable-json-patch'
13function updateDate2() {
14 const content = toJsonContent(myJsonEditor.get())
15 const updatedContent = setIn(content, ['json', 'lastEdited'], new Date().toISOString())
16 myJsonEditor.update(updatedContent)
17}
18
19// immutable change using the spread operator (not handy for updates in nested data)
20function updateDate3() {
21 const content = toJsonContent(myJsonEditor.get())
22 const updatedContent = {
23 json: {
24 ...content.json,
25 lastEdited: new Date().toISOString()
26 }
27 }
28 myJsonEditor.update(updatedContent)
29}
30
31// immutable change by creating a deep clone (simple though inefficient)
32import { cloneDeep } from 'lodash-es'
33function updateDate4() {
34 const content = toJsonContent(myJsonEditor.get())
35 const updatedContent = cloneDeep(content)
36 updatedContent.json.lastEdited = new Date().toISOString()
37 myJsonEditor.update(updatedContent)
38}
josdejong/svelte-jsoneditor
and josdejong/jsoneditor
This library josdejong/svelte-jsoneditor
is the successor of josdejong/jsoneditor
. The main differences are:
josdejong/jsoneditor | josdejong/svelte-jsoneditor | |
---|---|---|
Creation | Original (first published in 2011) | Successor (first published in 2021) |
Framework | Implemented in plain JavaScript, using low level DOM operations | Uses Svelte |
Tree mode | A tree view having context menu buttons on the left of every line. The keys and values are always in editable state. | A tree view utilizing right-click to open the context menu, and double-click to start editing a key or value (more similar to a Spreadsheet or text editor). It supports copy/paste from and to the system clipboard. |
Text mode | Powered by Ace editor | Powered by Code Mirror |
Preview mode | Used to preview large documents | Not needed, both tree and text mode can handle large documents |
The main reasons to create a new library instead of extending the existing one are:
josdejong/jsoneditor
is simple and straightforward, but also limited. The new tree mode of josdejong/svelte-jsoneditor
allows for much more streamlined editing and interaction. It works quite similar to a Spreadsheet or text editor. Navigate and select using the Arrow and Shift+Arrow keys or by dragging with the mouse. Double-click (or press Enter) to start editing a key or value. Open the context menu by right-clicking on the item or selection you want to operate on. Use cut/copy/paste to move parts of the JSON around and interoperate with other applications.When the library gives compile errors in your Svelte setup, it could be related to Vite having trouble importing ESM/CommonJS libraries the right way. The error could look like:
SyntaxError: The requested module '/node_modules/json-source-map/index.js?v=fda884be' does not provide an export named 'default' (at jsonUtils.js?v=fda884be:2:8)
A workaround is to add the following to your vite.config.js
file (read more):
1// ... 2 3/** @type {import('vite').UserConfig} */ 4const config = { 5 // ... 6 optimizeDeps: { 7 include: [ 8 'ajv-dist', 9 'immutable-json-patch', 10 'lodash-es', 11 '@fortawesome/free-regular-svg-icons', 12 'jmespath' 13 ] 14 } 15} 16 17// ...
To get started: clone the git repository, run npm install
, and then npm run dev
.
All available scripts:
npm install # Install dependencies (once)
npm run dev # Start the demo project (at http://localhost:5173)
npm run build # Build the library (output in ./package and ./package-vanilla)
npm run test # Run unit tests in watch mode
npm run test-ci # Run unit tests once
npm run coverage # Run unit test coverage (output in ./coverage)
npm run check # Run Svelte checks
npm run lint # Run linter
npm run format # Automatically fix linting issues
npm run release-dry-run # To run the build and see the change list without actually publishing
npm run release # Publish to npm (requires login). This will test, check, lint, build,
# increase the version number, update the changelog, and publish to npm.
# Note that it will publish two npm packages: `svelte-jsoneditor`
# and `vanilla-jsoneditor`.
svelte-jsoneditor
is released as open source under the permissive the ISC license.
If you are using svelte-jsoneditor
commercially, there is a social (but no legal) expectation that you help fund its maintenance. Start here.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
30 commit(s) and 23 issue activity found in the last 90 days -- score normalized to 10
Reason
security policy file detected
Details
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
1 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More