当前位置: 首页 > news >正文

JSONEditor 使用指南

JSONEditor 技术实践指南

JSONEditor 是一个基于 Web 的 JSON 编辑器组件、不需要任何的依赖,由 josdejong 开发维护,支持树形编辑代码编辑纯文本表单视图多种模式,广泛用于后台管理系统、API 调试工具、配置中心等场景。

github:https://github.com/josdejong/jsoneditor
npm:https://www.npmjs.com/package/jsoneditor
cdn:https://www.bootcdn.cn/jsoneditor/

模式概览

JSONEditor 的核心优势在于其提供了代码编辑 (code)纯文本 (text)表单视图 (form)树形编辑 (tree)只读视图 (view)五种模式,以适应不同的用户角色和编辑需求。

  • 树形 (tree) & 表单 (form) 模式:通过可视化节点和表单控件,极大降低了非技术背景用户(如运营、产品)编辑复杂JSON配置的心理门槛,非常适合后台管理系统配置中心
  • 代码 (code) 模式:提供语法高亮、括号匹配和实时校验,是开发者进行API调试、直接编写和修改JSON结构的首选。
  • 纯文本 (text) 模式:适用于处理非标准或大型JSON文本。
  • 只读 (view) 模式:用于安全地展示数据,如接口文档示例。

这种多模式设计,使得JSONEditor能够广泛服务于从开发、测试到运营的全流程,成为上述场景中处理JSON数据的通用解决方案。

一、核心

特性说明
多模式切换tree(树形)、code(代码)、form(表单)、text(文本)、view(只读)
JSON 校验实时语法检查,错误高亮 + 行号定位
搜索替换支持正则搜索,tree 模式支持 key/value 搜索
历史撤销内置 undo/redo
排序转换字段排序、JSON ↔ 数组互转
剪贴板复制/粘贴/剪切节点
零依赖不依赖任何框架,原生 JS 实现

二、引入

npm

npminstalljsoneditor
importJSONEditorfrom'jsoneditor';import'jsoneditor/dist/jsoneditor.min.css';

CDN

<scriptsrc="https://unpkg.com/jsoneditor@10.4.1/dist/jsoneditor.min.js"></script><linkhref="https://unpkg.com/jsoneditor@10.4.1/dist/jsoneditor.min.css"rel="stylesheet">

CDN 加载后,window.JSONEditor全局可用。

三、快速上手

初始化五步走

// 1. 准备容器constcontainer=document.getElementById('jsoneditor');// 2. 定义配置constoptions={mode:'tree',modes:['tree','code','form','text','view'],search:true,history:true,};// 3. 创建编辑器实例consteditor=newJSONEditor(container,options);// 4. 写入数据editor.set({name:'JSONEditor',version:'10.4.2',features:['tree','code','validate','format'],config:{theme:'default',readOnly:false,},});// 5. 读取数据constjson=editor.get();console.log(json);

HTML模板

<!DOCTYPEhtml><html><head><scriptsrc="https://unpkg.com/jsoneditor@10.4.1/dist/jsoneditor.min.js"></script><linkhref="https://unpkg.com/jsoneditor@10.4.1/dist/jsoneditor.min.css"rel="stylesheet"><style>#jsoneditor{width:100%;height:500px;}</style></head><body><divid="jsoneditor"></div><buttononclick="handleSave()">保存</button><script>constcontainer=document.getElementById('jsoneditor');consteditor=newJSONEditor(container,{mode:'code',modes:['tree','code'],});editor.set({hello:'world'});functionhandleSave(){constdata=editor.get();console.log('保存的数据:',JSON.stringify(data,null,2));}</script></body></html>

四、配置项

基础配置

constoptions={// 初始模式:tree | code | form | text | viewmode:'tree',// 允许用户切换的模式列表modes:['tree','code','form','text','view'],// 编辑器名称(多实例时标识)name:'configEditor',};

回调函数

constoptions={// JSON 内容变化时触发onChange:()=>{constjson=editor.get();console.log('内容已变更',json);},// 模式切换时触发onModeChange:(newMode,oldMode)=>{console.log(`模式从${oldMode}切换到${newMode}`);},// JSON 校验错误时触发onValidationError:(errors)=>{errors.forEach(err=>{console.error(`校验错误:${err.message}(位置:${err.path})`);});},// 编辑器加载完成onCreateMenu:(menu,node)=>{// 可自定义右键菜单returnmenu;},};

功能

constoptions={search:true,// 搜索框history:true,// 撤销/重做navigationBar:true,// 路径导航条statusBar:true,// 状态栏mainMenuBar:true,// 顶部主菜单sortObjectKeys:false,// 按 key 排序escapeUnicode:false,// 转义 UnicodeenableSort:true,// 允许排序enableTransform:true,// 允许类型转换};

只读与限制

constoptions={readOnly:false,// 全局只读limitDragging:false,// 禁止拖拽节点// 限制编辑深度(超过3层禁止编辑)onEditable:(node)=>{// node.path 为当前节点路径数组returnnode.path.length<=3;},// 限制最大可见节点数(性能保护)maxVisibleChilds:100,};

五、核心 API

数据操作

// 设置 JSON — 替换整个编辑器内容editor.set({key:'value'});// 获取 JSON — 返回 JS 对象constdata=editor.get();// 获取文本 — 返回格式化后的 JSON 字符串consttext=editor.getText();// 更新 — 与现有数据合并(仅 tree 模式)editor.update({newKey:'newValue'});// 注入新值 — 替换但不重置撤销历史editor.updateText('{"fresh": "data"}');

模式切换

// 切换到代码模式editor.setMode('code');// 获取当前模式constmode=editor.getMode();// 'tree' | 'code' | 'form' | 'text' | 'view'

节点操作(tree 模式)

// 展开全部节点editor.expandAll();// 折叠全部节点editor.collapseAll();// 聚焦到指定路径editor.focus();// 获取选中节点constnode=editor.getSelection();// 获取当前可编辑状态consteditable=editor.getEditable();

校验

// 手动触发校验consterrors=editor.validate();errors.forEach(err=>{// err.message — 错误描述// err.path — JSON 路径// err.line — 行号(code 模式)});

销毁

// 销毁编辑器实例,释放 DOM 和事件监听editor.destroy();

六、使用

组件封装

<template><div ref="container":style="{ height: height + 'px' }"></div></template><script>importJSONEditorfrom'jsoneditor';import'jsoneditor/dist/jsoneditor.min.css';exportdefault{props:{value:{type:[Object,Array],default:()=>({})},mode:{type:String,default:'tree'},modes:{type:Array,default:()=>['tree','code','view']},readOnly:{type:Boolean,default:false},height:{type:Number,default:400},},data(){return{editor:null};},watch:{value(val){if(val&&this.editor){this.editor.set(val);}},},mounted(){this.editor=newJSONEditor(this.$refs.container,{mode:this.mode,modes:this.modes,onChange:()=>{try{this.$emit('input',this.editor.get());}catch(e){}},});this.editor.set(this.value);},beforeDestroy(){this.editor?.destroy();},};</script>

表单中使用

// beforeOpen — 弹窗打开时初始化beforeOpen(done,type){getDetail(this.form.id).then((res)=>{this.form=res.data.data;letjsonObj={};try{jsonObj=JSON.parse(this.form.value);}catch(e){}this.$nextTick(()=>{constcontainer=document.getElementById('jsoneditor');if(container){if(this.editor)this.editor.destroy();this.editor=newJSONEditor(container,{mode:type==='view'?'view':'code',modes:['tree','code','view'],search:true,history:true,onChange:()=>{try{this.form.value=JSON.stringify(this.editor.get(),null,2);}catch(e){}},});this.editor.set(jsonObj);}});});done();},// beforeClose — 关闭时销毁beforeClose(done){if(this.editor){this.editor.destroy();this.editor=null;}done();},

七、各模式对比

模式适用场景可编辑特点
tree浏览复杂嵌套结构、对比数据可折叠/展开、拖拽排序节点
code直接编辑 JSON 源码语法高亮、行号、括号匹配
form非技术人员填写配置表单控件,字段级校验
text大文本处理纯文本,无高亮
view只读展示跟 tree 一样的树形,不可编辑

八、常见问题

Q: 如何限制用户只使用 tree 模式?
modes: ['tree'],工具条上的模式切换按钮只显示 tree。

Q: 如何设置初始展开深度?
无原生配置,editor.set(data)后调用editor.collapseAll()再手动展开顶层。

Q: onChange 触发太频繁?
用防抖包装:

onChange:debounce(()=>{this.form.value=JSON.stringify(this.editor.get(),null,2);},500),

Q: 如何自定义错误提示语言?

通过onValidationError回调自定义错误展示。

onValidationError:(errors)=>{errors.forEach(err=>{// 自定义错误显示,例如转换为中文提示alert(`校验错误:${err.message},位置:${err.path}`);});}

九、总结

JSONEditor 是 JSON 编辑场景的首选方案——API 简洁、功能完整、零依赖。tree 模式适合浏览复杂数据结构,code 模式适合开发人员直接编写 JSON,view 模式适合只读展示。配合 Vue/React 简单封装即可复用到各个模块。

http://www.jsqmd.com/news/845825/

相关文章:

  • QMCDecode:3步快速解密QQ音乐加密文件的终极指南
  • 实验室超纯水机哪个厂家好?2026 深度测评:四川沃特尔凭什么脱颖而出 - 品牌推荐大师
  • WinSW实战:除了开机自启,这样配置还能监控你的Nacos服务状态与日志
  • 2026 东莞松山湖科创企业融资机构实力榜|国委联稳居榜首,复杂融资首选 - 资讯焦点
  • 抖音批量下载器终极指南:如何高效获取无水印视频内容
  • 磁的基本概念
  • C-Eval:中文大模型能力评估的“高考”与诊断工具
  • Flowable任务分配实战:从静态指派到动态委派的进阶之路
  • 成都婚纱照品牌测评:瞳创摄影携2025行业数据与热门风格指南 - 资讯焦点
  • VScode玩转单片机:除了EIDE,这些插件也能帮你管理Keil/IAR/GCC项目
  • 2026深圳婚纱摄影排名|一线城市婚拍综合实力深测评 - 江湖评测
  • 软件测试中的持续集成与持续测试:Jenkins实战教程
  • 2026年洛阳短视频代运营与AI全域获客服务商深度评测:从流量到转化的完整闭环 - 精选优质企业推荐官
  • 告别内存泄漏!LabVIEW调用Halcon后必须做的资源释放操作(附HImage、HWindow关闭方法)
  • 十大电动门品牌财门:四大核心门型,构建全场景智慧出入口生态! - 资讯焦点
  • FanControl完全指南:Windows风扇智能控制终极方案
  • 电子签名怎么变成透明背景?手机和电脑端制作方法全整理|2026实测 - 软件小管家
  • 手把手教你用Keil5和PhyPlusKit玩转PHY6222蓝牙芯片的定时器例程
  • Taotoken平台用量看板与成本分析功能详解与操作指南
  • 从U盘启动OpenWRT:零门槛打造你的x86软路由实验平台
  • 告别Windows和TwinCAT:在树莓派上免费玩转EtherCAT主站,IgH配置全记录
  • 陕西人装外墙必看:EPS 线条 发泡陶瓷线条靠谱企业 + 选购避坑技巧 - 深度智识库
  • 中兴B860AV2.1-A刷机后实测:第三方桌面、去广告、装App,老旧盒子变身全能播放器
  • 2026哈密卫生间免砸砖防水、外墙、地下室、楼顶渗漏+彩钢瓦、阳光房隔热 本地专业防水公司TOP5权威推荐(2026年5月本地最新深度调研) - 防水百科
  • ToDesk配置文件config.ini全解析:从安全设置到代理配置,一篇搞定
  • 5个步骤快速掌握JPEXS Free Flash Decompiler字体替换完整教程
  • 滚齿机十大品牌综合排行:精度、质量、售后、口碑维度解析 - 品牌推荐大师1
  • 2026苏州名表回收机芯保养科普,定期养护提升残值 - 奢侈品回收测评
  • 院校智慧校园一体化平台采购选型指南:学工与教工系统统一建设方案
  • 从探索迷宫到攻克复杂环境:SAC算法如何用“最大熵”打破强化学习僵局