一種基於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 ,則有一個社交(但沒有法律)期望您可以幫助您的維護資金。從這裡開始。