一种基于Web的工具,可查看,编辑,格式,转换和验证JSON。
尝试:https://jsoneditoronline.org
该库是用Svelte编写的,但也可以在普通的JavaScript和任何框架中使用(SolidJ,React,Vue,Angular等)。它需要从2022年3月或更新的浏览器。
用于在一个Svelte项目中使用:
npm install svelte-jsoneditor
用于在香草JavaScript或SolidJ,React,Vue,Angular等的框架中使用:
npm install vanilla-jsoneditor
创建具有双向绑定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 >或单向绑定:
< 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: unknown } | { text: string }
console . log ( 'onChange: ' , { updatedContent , previousContent , contentErrors , patchResult } )
content = updatedContent
}
</ script >
< div >
< JSONEditor {content} onChange =" {handleChange} " />
</ div >该库通过NPM库vanilla-jsoneditor (而不是svelte-jsoneditor )提供了编辑器的香草包,该库可用于任何浏览器环境和框架。在诸如React,Vue或Angular之类的框架中,您需要在类界面上编写一些包装代码。
如果您使用捆绑器(例如Vite,lollup或webpack)为项目设置设置,则最好使用默认的ES导入:
// for use in a React, Vue, or Angular project
import { JSONEditor } from 'vanilla-jsoneditor'如果要在浏览器中直接使用库,请使用提供的独立ES捆绑包:
// for use directly in the browser
import { createJSONEditor } from 'vanilla-jsoneditor/standalone.js'独立的捆绑包包含vanilla-jsoneditor的所有依赖项,例如lodash-es和Ajv 。如果您在项目中也使用其中一些依赖项,则意味着它们将在您的Web应用程序中两次捆绑,从而导致不必要的应用程序大小。通常,最好是使用import { createJSONEditor } from 'vanilla-jsoneditor'以便可以重复使用依赖关系。
浏览器示例加载独立ES模块:
<!doctype html >
< html lang =" en " >
< head >
< title > JSONEditor </ title >
</ head >
< body >
< div id =" jsoneditor " > </ div >
< script type =" module " >
import { createJSONEditor } from 'vanilla-jsoneditor/standalone.js'
// Or use it through a CDN (not recommended for use in production):
// import { createJSONEditor } from 'https://unpkg.com/vanilla-jsoneditor/standalone.js'
// import { createJSONEditor } from 'https://cdn.jsdelivr.net/npm/vanilla-jsoneditor/standalone.js'
let content = {
text : undefined ,
json : {
greeting : 'Hello World'
}
}
const editor = createJSONEditor ( {
target : document . getElementById ( 'jsoneditor' ) ,
props : {
content ,
onChange : ( updatedContent , previousContent , { contentErrors , patchResult } ) => {
// content is an object { json: unknown } | { 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 >为了使您更容易在您选择的框架中使用库,您可以使用包装库:
Svelte组件:
< script >
import { JSONEditor } from 'svelte-jsoneditor'
let content = { text : '[1,2,3]' }
</ script >
< div >
< JSONEditor {content} />
</ div >Javasscript类:
import { createJSONEditor } from 'vanilla-jsoneditor' // or 'vanilla-jsoneditor/standalone.js'
const content = { text : '[1,2,3]' }
const editor = createJSONEditor ( {
target : document . getElementById ( 'jsoneditor' ) ,
props : {
content ,
onChange : ( updatedContent , previousContent , { contentErrors , patchResult } ) => {
// content is an object { json: unknown } | { text: string }
console . log ( 'onChange' , { updatedContent , previousContent , contentErrors , patchResult } )
}
}
} )content和mode之类的属性要么作为属性传递给Svelte组件,例如<JSONEditor {content} {mode} /> ,也可以通过props在vanilla js factory函数的情况下通过props:createjsoneditor: createJSONEditor({ target, props: { content, mode } 。
content: Content通过JSON内容在Jsoneditor中渲染。 Content是一个包含属性json (解析的JSON文档)或text (Stringifiend JSON文档)的对象。只能定义两个属性中的一个。您可以将两种内容类型传递给编辑器,而不是在哪种模式下将其传递给编辑器。您可以通过bind:content 。
重要的是:仅对
content进行不变的更改。可变的变化会弄乱历史并呈现内容。请参阅部分不变性。
selection: JSONEditorSelection | undefined当前选定的内容。您可以使用bind:selection使用双向绑定。 tree模式支持MultiSelection , KeySelection , EditKeySelection ,编辑, ValueSelection , EditValueSelection , InsideSelection或AfterSelection 。 table模式支持ValueSelection , text模式支持TextSelection. 。
mode: 'tree' | 'text' | 'table'以'tree'模式(默认), 'table'模式或'text'模式(以前: code模式)打开编辑器。
mainMenuBar: boolean显示主菜单栏。默认值是true 。
navigationBar: boolean显示导航栏,您可以在其中看到所选路径并从那里浏览文档。默认值是true 。
statusBar: boolean在'text'编辑器的底部显示状态栏,显示有关光标位置和选定内容的信息。默认值是true 。
askToFormat: boolean当true (默认值)时,将询问用户在加载或以'text'模式加载或粘贴的紧凑文档时是否要格式化JSON文档。仅适用于'text'模式。
readOnly: boolean在只读模式下打开编辑器:无法进行更改,在菜单中隐藏了非相关按钮,并且不启用上下文菜单。默认值为false 。
indentation: number | string串起JSON时的空间数量,或用作凹痕的字符串,例如't'将选项卡用作凹痕或使用4个' ' (等于配置indentation: 4 )。另请参见属性tabSize 。
tabSize: number当将凹痕配置为选项卡字符( indentation: 't' )时, tabSize配置了呈现的标签字符的大小。默认值为4 。仅适用于text模式。
escapeControlCharacters: boolean默认情况下为fals。如果true ,则将诸如newline和Tab之类的控制字符呈现为逃脱的字符n和t 。仅适用于'tree'模式,在'text'模式控制字符中总是被逃脱。
escapeUnicodeCharacters: boolean默认情况下为fals。当true时候,Unicode字符喜欢☎和?渲染如u260e和ud83dude00 。
flattenColumns: boolean默认情况下为true。仅适用于'table'模式。如果为true ,则将嵌套对象属性显示在自己的列中,并将嵌套路径作为列名显示。当false时,嵌套对象将被呈现在线,双击它们将在弹出窗口中打开它们。
validator : function ( json : unknown ) : ValidationError [ ]验证JSON文档。例如,使用由AJV驱动的内置JSON模式验证器:
import { createAjvValidator } from 'svelte-jsoneditor'
const validator = createAjvValidator ( { schema , schemaDefinitions } ) parser: JSON = JSON配置自定义JSON解析器,例如lossless-json 。默认情况下,使用JavaScript的本机JSON解析器。 JSON接口是具有parse stringify函数的对象。例如:
< 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仅在提供validator时适用。这与parser相同,除了该解析器在将数据发送给验证器之前用于解析数据。配置一个自定义的JSON解析器,该解析器用于将其传递给validator之前,该解析器用于解析JSON。默认情况下,使用内置的JSON解析器。传递自定义validationParser时,请确保解析器的输出由配置的validator支持。因此,当validationParser可以输出bigint号码或其他数字类型时, validator还必须支持这一点。在树模式下,当parser不等于validationParser时,JSON文档将在通过validationParser.parse(parser.stringify(json))传递给validator之前将其转换为验证器。
pathParser: JSONPathParser带有解析和弦乐方法的可选对象,用于解析和串起JSONPath ,这是带有属性名称的数组。 pathParser在导航栏中的路径编辑器中使用,该路径编辑器通过单击导航栏右侧的“编辑”按钮打开。当输入无效时,允许pathParser.parse函数丢弃错误。默认情况下,使用JSON路径符号,看起来像$.data[2].nested.property 。另外,可以使用例如/data/2/nested/property或定制的东西,例如JSON指针符号。相关的助手功能: parseJSONPath和stringifyJSONPath , parseJSONPointer和compileJSONPointer 。
onError ( err : Error )发生错误时触发回调。默认实现是记录控制台中的错误,并向用户显示一个简单的警报消息。
onChange ( content : Content , previousContent : Content , changeStatus : { contentErrors : ContentErrors | undefined , patchResult : JSONPatchResult | undefined } )对用户从编辑器内部进行的每次更改的内容进行调用的回调。它不会触发通过.set() ,. .update()或.patch()等方法编程应用的更改。
返回的content有时为类型{ json } ,有时为{ text }类型。返回的两个中的哪一个取决于编辑器的模式,所应用的更改以及文档的状态(有效,无效,空)。请注意, { text }可以包含无效的JSON:在text模式下键入时,JSON文档将暂时无效,就像用户键入新字符串时一样。参数patchResult仅在可以用作JSON补丁文档的更改上返回,例如,在text模式下自由键入时。
onChangeMode ( mode : 'tree' | 'text' | 'table' )在更改模式时调用。
onClassName ( path : JSONPath , value : any ) : string | undefined根据其路径和/或值,将自定义类名称添加到特定节点。请注意,在自定义类中,您可以覆盖CSS变量,例如--jse-contents-background-color以更改节点的样式,例如背景颜色。相关变量是:
--jse-contents-background-color
--jse-selection-background-color
--jse-selection-background-inactive-color
--jse-hover-background-color
--jse-context-menu-pointer-hover-background
--jse-context-menu-pointer-background
--jse-context-menu-pointer-background-highlight
--jse-collapsed-items-background-color
--jse-collapsed-items-selected-background-color为了调整键或值的文本颜色,可以覆盖类.jse-key和.jse-value的颜色。
onRenderValue ( props : RenderValueProps ) : RenderValueComponentDescription [ ]自定义值的渲染。默认情况下,使用了renderValue ,该值将值作为一个可编辑的div呈现,并取决于值,还可以呈现布尔式切换,颜色拾取器和时间戳标签。可以互相呈现多个组件,例如布尔式切换和从可编辑的Div渲染的颜色拾取器。为了禁用内置颜色拾取器或时间戳标签,您可以查找renderValue的源代码,复制它,然后删除您不需要从功能中的组件。内置的价值渲染器组件: EditableValue , ReadonlyValue , BooleanToggle , ColorPicker , TimestampTag , EnumValue 。
对于JSON模式枚举,有一个现成的值渲染器renderJSONSchemaEnum ,它使用EnumValue组件呈现枚举。可以像以下方式一样使用:
import { renderJSONSchemaEnum , renderValue } from 'svelte-jsoneditor'
function onRenderValue ( props ) {
// use the enum renderer, and fallback on the default renderer
return renderJSONSchemaEnum ( props , schema , schemaDefinitions ) || renderValue ( props )
}回调onRenderValue必须返回带有一个或多个渲染器的数组。每个渲染器都可以是苗条的组件,也可以是敏捷的动作:
interface SvelteComponentRenderer {
component : typeof SvelteComponent < RenderValuePropsOptional >
props : Record < string , unknown >
}
interface SvelteActionRenderer {
action : Action // Svelte Action
props : Record < string , unknown >
} SvelteComponentRenderer接口可用于提供像上面提到的EnumValue组件一样提供较小的组件。 SvelteActionRenderer期望将Svelte行动作为action属性。由于此接口是一个普通的JavaScript接口,因此可以在Vanilla JS环境中创建自定义组件。基本上,这是一个传递DOM节点的函数,并且需要返回具有update和destroy功能的对象:
const myRendererAction = {
action : ( node ) => {
// attach something to the HTML DOM node
return {
update : ( node ) => {
// update the DOM
} ,
destroy : ( ) => {
// cleanup the DOM
}
}
}
} onRenderMenu ( items : MenuItem [ ] , context : { mode : 'tree' | 'text' | 'table' , modal : boolean , readOnly : boolean } ) : MenuItem [ ] | undefined可用于更改菜单项的回调。可以添加新项目,也可以删除或重组现有项目。当功能返回undefined时,将应用原始items 。
使用上下文值mode , modal和readOnly ,可以根据编辑器的模式以及编辑器是否在模态内渲染,或者取决于是否仅读取它。
菜单项MenuItem可以是以下类型之一:
按钮:
interface MenuButton {
type : 'button'
onClick : ( ) => void
icon ?: IconDefinition
text ?: string
title ?: string
className ?: string
disabled ?: boolean
}分离器(一组项目之间的灰色垂直线):
interface MenuSeparator {
type : 'separator'
}空间(填满空白空间):
interface MenuSpace {
type : 'space'
} onRenderContextMenu ( items : ContextMenuItem [ ] , context : { mode : 'tree' | 'text' | 'table' , modal : boolean , readOnly : boolean , selection : JSONEditorSelection | undefined } ) : ContextMenuItem [ ] | false | undefined可用于更改上下文菜单项的回调。可以添加新项目,也可以删除或重组现有项目。当功能返回undefined时,将应用原始items ,并且当readOnly为false时将显示上下文菜单。当功能返回false时,上下文菜单将永远不会显示。当编辑器被readOnly时,也会触发回调,在大多数情况下,您想返回false 。
使用上下文值mode , modal , readOnly和selection ,可以根据编辑器的模式采取不同的操作,无论编辑器是否在模态内渲染,无论编辑器是否仅读取,并且取决于选择路径。
菜单项ContextMenuItem可以是以下类型之一:
按钮:
interface MenuButton {
type : 'button'
onClick : ( ) => void
icon ?: IconDefinition
text ?: string
title ?: string
className ?: string
disabled ?: boolean
}下拉按钮:
interface MenuDropDownButton {
type : 'dropdown-button'
main : MenuButton
width ?: string
items : MenuButton [ ]
}分离器(一组项目之间的灰色线):
interface MenuSeparator {
type : 'separator'
}菜单行和列:
interface MenuLabel {
type : 'label'
text : string
}
interface ContextMenuColumn {
type : 'column'
items : Array < MenuButton | MenuDropDownButton | MenuLabel | MenuSeparator >
}
interface ContextMenuRow {
type : 'row'
items : Array < MenuButton | MenuDropDownButton | ContextMenuColumn >
} onSelect : ( selection : JSONEditorSelection | undefined ) => void选择选择时调用回调。删除选择时,将回调用undefined参数调用。在text模式下,将发出TextSelection 。在tree和table模式下,将触发JSONSelection (可以进行MultiSelection , KeySelection ,按键, EditKeySelection , ValueSelection , EditValueSelection ,inturevalueSelection, InsideSelection或AfterSelection )。使用isTextSelection和isValueSelection之类的类型款来检查选择的类型。
queryLanguages: QueryLanguage [ ]配置可以在变换模式中使用的一种或多种查询语言。该库带有以下语言:
这些语言可以如下加载:
import {
jsonQueryLanguage ,
jmespathQueryLanguage ,
jsonpathQueryLanguage ,
lodashQueryLanguage ,
javascriptQueryLanguage
} from 'svelte-jsoneditor'
const allQueryLanguages = [
jsonQueryLanguage ,
jmespathQueryLanguage ,
jsonpathQueryLanguage ,
lodashQueryLanguage ,
javascriptQueryLanguage
]默认情况下,编辑器中仅加载了jsonQueryLanguage 。
请注意, lodashQueryLanguage和javascriptQueryLanguage都可以执行任意JavaScript代码,并使用new Function(...)执行代码。因此,由于安全风险,它们通常不适合存储或共享查询。在某些环境中,尝试使用它们将导致CSP(内容安全策略)错误,具体取决于安全策略。
queryLanguageId: string当前选择的查询语言的id 。
onChangeQueryLanguage : ( queryLanguageId : string ) => void当用户通过配置按钮右上方更改“转换”中所选查询语言时调用回调函数。
onFocus()回调。onBlur()回调了。可以在JSONEDITOR实例上调用方法。在Svelte中,您可以创建参考并调用类似的方法:
< script >
let editor
function logContents () {
const content = editor . get () // using a method
console . log (content)
}
</ script >
< JSONEditor bind:this ={ editor } />在香草编辑器中,使用出厂功能来创建一个编辑器实例:
const editor = createJSONEditor ( { ... } )
function logContents ( ) {
const content = editor . get ( ) // using a method
console . log ( content )
}请注意,大多数方法是异步的,并且在重新渲染编辑器后将解决(在下一个tick上)。
JSONEditor . prototype . get ( ) : Content获取当前的JSON文档。
重要的是:不要突变收到的
content,这会弄乱历史并呈现内容。请参阅部分不变性。
JSONEditor . prototype . set ( content : Content ) : Promise < void >替换当前内容。将重置编辑器的状态。另请参见方法update(content) 。
JSONEditor . prototype . update ( content : Content ) : Promise < void >更新已加载的内容,以保持编辑器的状态(例如扩展的对象)。您也可以调用editor.updateProps({ content }) 。另请参见方法set(content) 。
重要的是:仅对
content应用不变的更改。可变的变化会弄乱历史并呈现内容。请参阅部分不变性。
JSONEditor . prototype . patch ( operations : JSONPatchDocument ) : Promise < JSONPatchResult >应用JSON补丁文档以更新JSON文档的内容。 JSON补丁文档是带有JSON补丁操作的列表。
重要的是:仅对内容物应用不变的更改。可变的变化会弄乱历史并呈现内容。请参阅部分不变性。
JSONEditor . prototype . updateProps ( props : Object ) : Promise < void > tpdate一些或全部属性。更新的content也可以传递;这等同于调用update(content) 。例子:
editor . updateProps ( {
readOnly : true
} ) JSONEditor . prototype . expand ( path : JSONPath , callback ?: ( relativePath : JSONPath ) = > boolean = expandSelf ) : Promise < void >在编辑器中扩展或崩溃路径。所提供path沿线的所有节点将被扩展并变得可见(渲染)。因此,例如,将扩展阵列的崩溃部分。使用可选callback ,也可以扩展节点本身及其某些或所有嵌套子节点。 callback函数仅在数组的可见部分上迭代,而不是在任何折叠部分上迭代。默认情况下,阵列的前100个项目可见并渲染。
示例:
editor.expand([], () => true)展开全部editor.expand([], relativePath => relativePath.length < 2)将所有路径扩展到最高2个级别editor.expand(['array', '204'])扩展根对象,该对象中的数组以及数组中的第204个项目。editor.expand(['array', '204'], () => false)扩展了根对象,该对象中的数组,但不是204个项目本身。editor.expand(['array', '204'], relativePath => relativePath.length < 2)扩展根对象,该对象中的数组,并将204个阵列项目及其所有孩子扩展到最大2级别的深度。该库导出了一些常用callback功能的实用程序功能:
expandAll :递归扩展所有嵌套对象和数组。expandNone :没有扩展,也不是根对象或数组。expandSelf :扩展根数组或对象。这是callback参数的默认值。expandMinimal :扩展根数组或对象,如果数组,则展开第一个数组项目。 JSONEditor . prototype . collapse ( path : JSONPath , recursive ?: boolean = false ) : Promise < void >崩溃编辑器中的路径。当recursive是true时,所有嵌套的对象和数组也会崩溃。 recursive的默认值是false 。
JSONEditor . prototype . transform ( { id ?: string , rootPath ?: [ ] , onTransform : ( { operations : JSONPatchDocument , json : unknown , transformedJson : unknown } ) => void , onClose : ( ) => void } )通过编程性触发主菜单中“转换”按钮的单击,打开“变换”模型。如果提供了回调onTransform ,它将替换建立逻辑以应用转换,从而使您可以替代方式处理转换操作。如果提供,则在转换模态关闭时, onClose回调将触发,在用户单击时,请应用或取消。如果提供了id ,则转换模式将加载此id的先前状态,而不是编辑器变换模式的状态。
JSONEditor . prototype . scrollTo ( path : JSONPath ) : Promise < void >垂直滚动编辑器,以使指定的路径进入视图。仅适用于模式tree和table 。路径将在需要时扩展。滚动完成后,返回的承诺将解决。
JSONEditor . prototype . findElement ( path : JSONPath )找到给定路径的DOM元素。当找不到时返回null 。
JSONEditor . prototype . acceptAutoRepair ( ) : Promise < Content >在树模式下,加载时会自动修复无效的JSON。维修成功后,修复后的内容将渲染,但尚未应用于文档本身,直到用户单击“确定”或开始编辑数据。用户也可以单击“手动维修”,而不是接受维修。调用.acceptAutoRepair()将在编程中接受维修。这将触发更新,该方法本身还返回更新的内容。如果发生text模式或编辑器不处于“接受自动修复”状态时,将什么都不会发生,并且内容将按原样返回。
JSONEditor . prototype . refresh ( ) : Promise < void >刷新内容的渲染,例如更改字体大小后。这仅在text模式下可用。
JSONEditor . prototype . validate ( ) : ContentErrors | undefined获取当前的所有解析错误和验证错误。
JSONEditor . prototype . select ( newSelection : JSONEditorSelection | undefined )更改当前选择。另请参见选项selection 。
JSONEditor . prototype . focus ( ) : Promise < void >给编辑重点。
JSONEditor . prototype . destroy ( ) : Promise < void >销毁编辑器,将其从DOM中删除。
库导出一组实用程序功能。这些功能的确切定义可以在打字稿D中找到
renderValuerenderJSONSchemaEnumBooleanToggleColorPickerEditableValueEnumValueReadonlyValueTimestampTaggetValueClasskeyComboFromEventcreateAjvValidatorjsonQueryLanguagejmespathQueryLanguagelodashQueryLanguagejavascriptQueryLanguageisContentisTextContentisJSONContentisLargeContenttoTextContenttoJSONContentestimateSerializedSizeexpandAllexpandMinimalexpandNoneexpandSelfisValueSelectionisKeySelectionisInsideSelectionisAfterSelectionisMultiSelection ,isEditingSelectioncreateValueSelectioncreateEditValueSelectioncreateKeySelectioncreateEditKeySelectioncreateInsideSelection ,createAfterSelectioncreateMultiSelectiongetFocusPathgetAnchorPathgetStartPathgetEndPathgetSelectionPathsisEqualParserparseJSONPathstringifyJSONPathresizeObserveronEscapevalueTypestringConvertisObjectisObjectOrArrayisBooleanisTimestampisColorisUrlisContentParseErrorisContentValidationErrorsimmutable-json-patch并使用其功能:immutableJSONPatchrevertJSONPatchparseJSONPointerparsePathparseFromcompileJSONPointercompileJSONPointerPropgetInsetInupdateIninsertAtexistsIndeleteIn在以下源文件中定义了打字稿类型(例如Content , JSONSelection和JSONPatchOperation ):
https://github.com/josdejong/svelte-jsoneditor/blob/main/src/lib/types.ts
编辑器可以使用可用的CSS变量进行样式。所有变量的完整列表可以在此处找到:
https://github.com/josdejong/svelte-jsoneditor/blob/main/src/lib/themes/defaults.scss
例如,将默认的蓝色主题颜色更改为无烟煤:
< script >
import { JSONEditor } from 'svelte-jsoneditor'
let content = {
text : undefined , // can be used to pass a stringified JSON document instead
json : {
string : 'Hello custom theme color :)'
}
}
</ script >
< div class =" my-json-editor " >
< JSONEditor bind:content />
</ div >
< style >
.my-json-editor {
/* define a custom theme color */
--jse-theme-color: #383e42;
--jse-theme-color-highlight: #687177;
}
</ style >编辑器带有一个内置的黑暗主题。使用此主题:
themes/jse-theme-dark.cssjse-theme-dark添加到加载编辑器的HTML容器元素中。可以加载多个主题的样式,并通过更改附加到HTML容器元素的类名(例如jse-theme-dark )来切换它们。
完整的Svelte示例:
< script >
import { JSONEditor } from 'svelte-jsoneditor'
let content = {
text : undefined , // can be used to pass a stringified JSON document instead
json : {
string : 'Hello dark theme :)'
}
}
</ script >
<!-- use a theme by adding its name to the container class -->
< div class =" my-json-editor jse-theme-dark " >
< JSONEditor bind:content />
</ div >
< style >
/* load one or multiple themes */
@import 'svelte-jsoneditor/themes/jse-theme-dark.css';
</ style >当动态更新CSS变量时,有必要刷新Via editorRef.refresh()以更新排水沟中的线号的字体大小,并在text模式下更新凹痕标记的颜色:
< script >
let editorRef
function refresh ( ) {
editorRef ?. refresh ( )
}
</ script >
< JSONEditor bind:this =" {editorRef} " ... /> 重要的是,只有以不可变的方式更新编辑器的content 。突变content将破坏历史记录(撤消/重做),并且不会总是根据更改立即更新用户界面。
需要变不变的原因是:
不变的工作方式的其他优点是,它使您可以使用更具预测性且容易出错的数据来使数据工作。您可以通过搜索有关该主题的文章或视频(例如本视频或本文)来了解有关不变性的更多信息。不变性并不总是最好的选择,但是在此JSON编辑器的情况下,我们正在处理大型嵌套的数据结构,通常我们通常只做一些小更改,例如更新单个嵌套值。不变的方法确实在这里闪耀,使svelte-jsoneditor可以平稳地渲染和编辑JSON文档,最高为512 MB。
这是一个可变变化的示例:
// mutable change (NOT SUPPORTED!)
function updateDate ( ) {
const lastEdited = new Date ( ) . toISOString ( )
const content = toJsonContent ( myJsonEditor . get ( ) )
content . json . lastEdited = lastEdited // <- this is a mutable change
myJsonEditor . update ( content )
// ERROR: The UI will not update immediately but only update after changing something
// inside the editor like the selection. And most importantly, history is broken now,
// because the original document is mutated. You cannot undo this action.
}相反,您可以以不可变的方式应用相同的更改。有多种选择:
// immutable change using a libary like "mutative" or "immer" (efficient and easy to work with)
import { create } from 'mutative'
function updateDate1 ( ) {
const content = toJsonContent ( myJsonEditor . get ( ) )
const updatedContent = create ( content , ( draft ) => {
draft . json . lastEdited = new Date ( ) . toISOString ( )
} )
myJsonEditor . update ( updatedContent )
}
// immutable change using "immutable-json-patch"
import { setIn } from 'immutable-json-patch'
function updateDate2 ( ) {
const content = toJsonContent ( myJsonEditor . get ( ) )
const updatedContent = setIn ( content , [ 'json' , 'lastEdited' ] , new Date ( ) . toISOString ( ) )
myJsonEditor . update ( updatedContent )
}
// immutable change using the spread operator (not handy for updates in nested data)
function updateDate3 ( ) {
const content = toJsonContent ( myJsonEditor . get ( ) )
const updatedContent = {
json : {
... content . json ,
lastEdited : new Date ( ) . toISOString ( )
}
}
myJsonEditor . update ( updatedContent )
}
// immutable change by creating a deep clone (simple though inefficient)
import { cloneDeep } from 'lodash-es'
function updateDate4 ( ) {
const content = toJsonContent ( myJsonEditor . get ( ) )
const updatedContent = cloneDeep ( content )
updatedContent . json . lastEdited = new Date ( ) . toISOString ( )
myJsonEditor . update ( updatedContent )
} josdejong/svelte-jsoneditor与josdejong/jsoneditor之间的差异该图书馆josdejong/svelte-jsoneditor是josdejong/jsoneditor的继任者。主要区别是:
josdejong/jsoneditor | josdejong/svelte-jsoneditor | |
|---|---|---|
| 创建 | 原始(首次出版于2011年) | 继任者(于2021年首次出版) |
| 框架 | 使用低级DOM操作在平原JavaScript中实现 | 使用Svelte |
| 树模式 | 每行左侧的上下文菜单按钮的树视图。钥匙和值始终处于可编辑状态。 | 使用右键单击的树视图打开上下文菜单,并双击以开始编辑键或值(更类似于电子表格或文本编辑器)。它支持来自系统剪贴板的复制/粘贴。 |
| 文本模式 | 由ACE编辑提供支持 | 由代码镜提供动力 |
| 预览模式 | 用于预览大文档 | 不需要, tree和text模式都可以处理大型文档 |
创建新库而不是扩展现有图书馆的主要原因是:
josdejong/jsoneditor的经典树模式简单明了,但也有限。 josdejong/svelte-jsoneditor的新树模式允许更简化的编辑和交互。它的工作原理与电子表格或文本编辑器非常相似。使用箭头和Shift+Arrow键进行导航和选择,或者使用鼠标拖动。双击(或按Enter)开始编辑键或值。通过右键单击要操作的项目或选择,打开上下文菜单。使用切割/复制/粘贴将JSON的部分移动并与其他应用程序互操作。当库在Svelte设置中给出编译错误时,它可能与VITE以正确的方式导入ESM/COONCORJS库的问题有关。错误看起来像:
SyntaxError:请求的模块'/node_modules/json-source-map/index.js?v=fda884be'不提供名为'default''的导出(在jsonutils.js?v = fda884be:fda884be:2:8)
解决方法是将以下内容添加到您的vite.config.js文件(阅读更多):
// ...
/** @type {import('vite').UserConfig} */
const config = {
// ...
optimizeDeps : {
include : [
'ajv-dist' ,
'immutable-json-patch' ,
'lodash-es' ,
'@fortawesome/free-regular-svg-icons' ,
'jmespath'
]
}
}
// ... 开始:克隆GIT存储库,运行npm install ,然后npm run dev 。
所有可用脚本:
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在允许的ISC许可证下作为开源。
如果您在商业上使用svelte-jsoneditor ,则有一个社交(但没有法律)期望您可以帮助您的维护资金。从这里开始。