JSON을보고, 편집, 형식, 변환 및 검증하는 웹 기반 도구.
시도해보십시오 : https://jsoneditoronline.org
라이브러리는 svelte로 작성되었지만 일반 JavaScript와 모든 프레임 워크 (solidjs, reft, vue, angular 등)에서도 사용할 수 있습니다. 2022 년 3 월 또는 새로운 브라우저가 필요합니다.
Svelte 프로젝트의 사용을 위해 :
npm install svelte-jsoneditor
바닐라 JavaScript 또는 SolidJS, React, Vue, Angular 등과 같은 프레임 워크의 사용을 위해 :
npm install vanilla-jsoneditor
양방향 바인딩 bind:json : JSONEDITOR를 만듭니다.
< 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와 같은 프레임 워크에서는 클래스 인터페이스에 래퍼 코드를 작성해야합니다.
Bundler (Vite, Rollup 또는 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 포함되어 있습니다. 프로젝트에서 이러한 종속성 중 일부를 사용하는 경우 웹 애플리케이션에서 두 번 번들로 연결되어 불필요하게 큰 응용 프로그램 크기가 발생합니다. 일반적으로 독립형 번들 대신 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 와 같은 속성은 <JSONEditor {content} {mode} /> 와 같은 Svelte 구성 요소의 속성으로 전달되거나 바닐라 JS 공장 기능의 경우 props 통해 createJSONEditor({ target, props: { content, mode } .
content: Content JSONEDITOR에서 렌더링 할 JSON 내용을 전달하십시오. Content json (Parsed JSON 문서) 또는 text (Stringified 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 기본적으로 거짓. true 경우 Newline 및 Tab과 같은 제어 문자는 이스케이프 문자 n 및 t 로 렌더링됩니다. 'text' 'tree' '모드에만 적용됩니다.
escapeUnicodeCharacters: boolean 기본적으로 거짓. true , 유니 코드 문자는 ☎ 및? u260e 및 ud83dude00 처럼 탈출됩니다.
flattenColumns: boolean 기본적으로 사실입니다. 'table' 모드에만 적용됩니다. true 때 중첩 된 객체 속성은 각각 자체 열에 표시되며 중첩 경로는 열 이름으로 표시됩니다. false 있으면 중첩 된 물체가 인라인으로 렌더링되며 두 번 클릭하면 팝업에서 열립니다.
validator : function ( json : unknown ) : ValidationError [ ]JSON 문서를 확인하십시오. 예를 들어 AJV에서 전원을 공급하는 내장 JSON 스키마 유효성 검사기를 사용하십시오.
import { createAjvValidator } from 'svelte-jsoneditor'
const validator = createAjvValidator ( { schema , schemaDefinitions } ) parser: JSON = JSON lossless-json 과 같은 사용자 정의 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 파서를 구성하십시오. 기본적으로 내장 JSON 파서가 사용됩니다. Custom validationParser 통과 할 때는 구성된 validator 에서 구문 분석기의 출력이 지원되는지 확인하십시오. 따라서 validationParser bigint 숫자 또는 기타 숫자 유형을 출력 할 수있는 경우 validator 기도이를 지원해야합니다. 트리 모드에서 parser validationParser 와 같지 않은 경우 JSON 문서는 validationParser.parse(parser.stringify(json)) 통해 validator 로 전달되기 전에 변환됩니다.
pathParser: JSONPathParser Parse and Stringify 메소드가있는 선택적 객체는 JSONPath 구문 분석하고 stringify로, 속성 이름을 가진 배열입니다. pathParser 내비게이션 바의 오른쪽에있는 편집 버튼을 클릭하여 열린 내비게이션 바의 PATH 편집기에 사용됩니다. pathParser.parse 함수는 입력이 유효하지 않을 때 오류를 던질 수 있습니다. 기본적으로 JSON 경로 표기법이 $.data[2].nested.property 처럼 보입니다. 또는 예를 들어 /data/2/nested/property 같은 JSON 포인터 표기법 또는 맞춤 제작과 같은 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 경로 및/또는 값에 따라 특정 노드에 사용자 정의 클래스 이름을 추가하십시오. 사용자 정의 클래스에서는 --jse-contents-background-color 와 같은 CSS 변수를 무시하여 배경색과 같은 노드 스타일을 변경할 수 있습니다. 관련 변수는 다음과 같습니다.
--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로 값을 렌더링하고 값에 따라 부울 토글, 컬러 피커 및 타임 스탬프 태그를 렌더링 할 수 있습니다. 부울 토글과 컬러 피커와 같이 여러 구성 요소를 서로 렌더링 할 수 있습니다. 예를 들어 내장 된 컬러 피커 또는 타임 스탬프 태그를 비활성화하려면 renderValue 소스 코드를 찾아 복사 한 다음 기능에서 원하지 않는 구성 요소를 제거 할 수 있습니다. 내장 값 렌더러 구성 요소 : EditableValue , ReadonlyValue , BooleanToggle , ColorPicker , TimestampTag , EnumValue .
JSON 스키마 열거의 EnumValue , 기성품 값 렌더러 renderJSONSchemaEnum 이 있습니다. 이것은 다음과 같이 사용할 수 있습니다.
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 구성 요소와 같은 Svelte 구성 요소를 제공하는 데 사용될 수 있습니다. SvelteActionRenderer 는 action 속성으로서의 벨트 행동을 기대합니다. 이 인터페이스는 일반 JavaScript 인터페이스이므로 바닐라 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 , 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에서 제거하십시오.
라이브러리는 일련의 유틸리티 기능을 내 보냅니다. 이러한 함수의 정확한 정의는 TypeScript D에서 찾을 수 있습니다.
renderValuerenderJSONSchemaEnumBooleanToggleColorPickerEditableValueEnumValueReadonlyValueTimestampTaggetValueClasskeyComboFromEventcreateAjvValidatorjsonQueryLanguagejmespathQueryLanguagelodashQueryLanguagejavascriptQueryLanguageisContentisTextContentisJSONContentisLargeContenttoTextContenttoJSONContentestimateSerializedSizeexpandAllexpandMinimalexpandNoneexpandSelfisValueSelectionisKeySelectionisInsideSelectionisAfterSelectionisMultiSelection ,isEditingSelectioncreateValueSelectioncreateEditValueSelectioncreateKeySelectioncreateEditKeySelectioncreateInsideSelection ,createAfterSelectioncreateMultiSelectiongetFocusPathgetAnchorPathgetStartPathgetEndPathgetSelectionPathsisEqualParserparseJSONPathstringifyJSONPathresizeObserveronEscapevalueTypestringConvertisObjectisObjectOrArrayisBooleanisTimestampisColorisUrlisContentParseErrorisContentValidationErrorsimmutable-json-patch 설치하고 그 기능을 사용할 수 있습니다.immutableJSONPatchrevertJSONPatchparseJSONPointerparsePathparseFromcompileJSONPointercompileJSONPointerPropgetInsetInupdateIninsertAtexistsIndeleteIn TypeScript 유형 ( 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 )을 변경하여 전환 할 수 있습니다.
완전한 예제 :
< 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 변수를 동적 text 업데이트 editorRef.refresh() 때는 gut
< script >
let editorRef
function refresh ( ) {
editorRef ?. refresh ( )
}
</ script >
< JSONEditor bind:this =" {editorRef} " ... /> 편집자의 content 불변으로 만 업데이트되는 것이 중요합니다. content 돌리면 히스토리 (실행 취소/Redo)가 깨지며 변경 사항에 따라 항상 사용자 인터페이스를 즉시 업데이트하지는 않습니다.
불변의 변화를 요구하는 이유는 다음과 같습니다.
불변의 작업 방식의 다른 장점은 예측적이고 오류가 적게 발생하는 데이터를 만듭니다. 이 비디오 또는이 기사와 같은 주제에 대한 기사 나 비디오를 검색하여 불변성에 대한 자세한 내용을 배울 수 있습니다. 불변성이 항상 최선의 선택은 아니지만,이 JSON 편집기의 경우, 우리는 크고 깊은 중첩 된 데이터 구조를 다루고 있으며, 이는 일반적으로 단일 중첩 값을 업데이트하는 것과 같은 작은 변경 만합니다. 불변의 접근 방식은 실제로 여기에서 빛나며 svelte-jsoneditor JSON 문서를 최대 512MB까지 원활하게 렌더링하고 편집 할 수 있습니다.
다음은 변이 가능한 변화의 예입니다.
// 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 의 새로운 트리 모드는 훨씬 더 간소화 된 편집 및 상호 작용을 허용합니다. 스프레드 시트 또는 텍스트 편집기와 매우 유사하게 작동합니다. 화살표 및 변속+화살표 키를 사용하거나 마우스로 드래그하여 탐색하고 선택하십시오. 키 또는 값 편집을 시작하려면 두 번 클릭 (또는 Enter를 누르십시오). 작업중인 항목이나 선택을 마우스 오른쪽 버튼으로 클릭하여 컨텍스트 메뉴를 엽니 다. 컷/복사/붙여 넣기를 사용하여 JSON의 일부를 이동하고 다른 응용 프로그램과 상호 운용하십시오.라이브러리가 Svelte 설정에서 컴파일 오류를 제공하면 ESM/CommonJS 라이브러리를 올바른 방법으로 가져 오는 데 어려움을 겪는 VITE와 관련이있을 수 있습니다. 오류는 다음과 같습니다.
SyntaxError : 요청 된 모듈 '/node_modules/json-source-map/index.js?v=fda884be'는 'default'(at jsonutils.js? v = 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 사용하는 경우 유지 보수에 자금을 지원하는 데 도움이 될 사회적으로 (그러나 법적은) 기대가 있습니다. 여기서 시작하십시오.