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

原生JS写一个JSON格式化工具

        JSON在线压缩功能,适配所有框架,轻量便捷。支持压缩、格式化、校验功能,并且能标记错误位置,话不多说,上架。。。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Editor</title>
<style>
    body {
        font-family: Arial, sans-serif;
        margin: 20px;
    }
    .json_edit{
        width: 100%;
    }
    .json_edit .text_contant {
        width: 100%;
        height: 300px;
        border: 1px solid #ccc;
        padding: 10px;
        font-size: 14px;
        outline: none;
        font-family: monospace;
    }
    .json_edit .optionBtn {
        padding: 10px 15px;
        margin: 5px;
        background-color: #007bff;
        color: #fff;
        border: none;
        cursor: pointer;
        font-size: 14px;
    }
    .json_edit #toolTop {
        margin-top: 20px;
        padding: 10px;
        background: #f9f9f9;
        white-space: pre-wrap;
        color: #ff4343;
    }
    .json_edit .optionBtn:hover {
        background-color: #0056b3;
    }

    .json_edit .error {
        border: 2px solid #ff4343;
        background-color: #ffe6e6;
    }
    .json_edit .error_content {
        background-color: #ffcccc;
        color: #ff4343;
        font-weight: bold;
    }
    .json_edit .line_number {
        display: inline-block;
        width: 30px;
        text-align: right;
        margin-right: 10px;
        color: #888;
        font-size: 13px
    }
    
    
</style>
</head>
<body>
    <div class="json_edit">
        <textarea class="text_contant" id="textareaInput" oninput="clearError()"></textarea>
        <button class="optionBtn" onclick="formatJSON()">格式化JSON</button>
        <button class="optionBtn" onclick="compressJson()">压缩JSON</button>
        <div id="toolTop"></div>
    </div>

    <script>
        const validJSON = (str) => {
            try {
                const obj = JSON.parse(str);
                return typeof obj === 'object' && obj !== null && (Array.isArray(obj) || Object.prototype.toString.call(obj) === '[object Object]');
            } catch (e) {
                return false;
            }
        }
        // 格式化json操作
        const formatJSON = ()=> {
            const textareaInput = document.getElementById('textareaInput');
            const toolTop = document.getElementById('toolTop');
            if (!textareaInput.value) {
                return 
            }
            if (!validJSON(textareaInput.value)) {
                markError(new Error('JSON格式错误!'), textareaInput);
                return;
            }
            try {
                const jsonObj = JSON.parse(textareaInput.value);
                textareaInput.value = JSON.stringify(jsonObj, null, 2);
                textareaInput.classList.remove('error');
                toolTop.textContent = '格式化成功!';
                toolTop.style.color = '#12a793';
            } catch (error) {
                markError(error, textareaInput);
                toolTop.textContent = 'JSON格式错误:' + error.message;
                toolTop.style.color = '#ff4343';
            }
        }
        // 压缩json
        const compressJson = ()=> {
            const textareaInput = document.getElementById('textareaInput');
            const toolTop = document.getElementById('toolTop');
            if (!textareaInput.value) {
                return 
            }
            if (!validJSON(textareaInput.value)) {
                markError(new Error('JSON格式错误!'), textareaInput);
                return;
            }
            try {
                const jsonObj = JSON.parse(textareaInput.value);
                textareaInput.value = JSON.stringify(jsonObj);
                textareaInput.classList.remove('error');
                toolTop.textContent = '压缩成功!';
                toolTop.style.color = '#12a793';
            } catch (error) {
                markError(error, textareaInput);
                toolTop.textContent = 'JSON格式错误:' + error.message;
                toolTop.style.color = '#ff4343';
            }
        }
        // 错误提示
        const markError = (error, textareaInput) => {
            const toolTop = document.getElementById('toolTop');
            textareaInput.classList.add('error');
            let text = textareaInput.value;
            try {
                JSON.parse(text);
            } catch (e) {
                let match = e.message.match(/position (\d+)/);
                if (match) {
                    let pos = parseInt(match[1]);
                    let lines = text.substring(0, pos).split('\n');
                    let line = lines.length;
                    let column = lines[lines.length - 1].length + 1;
                    let errorChar = text[pos] || ' ';
                    let formattedText = text.split('\n').map((l, i) => {
                        return `<span class="line_number">${i + 1}</span>${l}`;
                    }).join('\n');
                    let highlightedText = formattedText.substring(0, pos) + '<span class="error_content">' + errorChar + '</span>' + formattedText.substring(pos + 1);
                    toolTop.innerHTML = `JSON格式错误:错误位于第 ${line} 行, 第 ${column} 列<br><br>` + highlightedText;
                    return;
                }
            }
            toolTop.textContent = 'JSON格式错误:' + error.message;
            toolTop.style.color = '#ff4343';
        }

        // 清空error
        const clearError = ()=> {
            document.getElementById('textareaInput').classList.remove('error');
            document.getElementById('toolTop').textContent = '';
        }
    </script>
</body>
</html>

http://www.dtcms.com/a/109962.html

相关文章:

  • LeeCode 5. 最长回文字串
  • QT Quick(C++)跨平台应用程序项目实战教程 6 — 弹出框
  • UE5学习笔记 FPS游戏制作40 制作鼠标移入UI显示提示背景色的效果
  • C 语言中的递归:概念、应用与实例解析
  • 3D动画动作捕捉设备:惯性动捕赋能轻量级影视动画创作
  • Python Cookbook-5.1 对字典排序
  • 新版本AndroidStudio配置maven阿里云镜像
  • AI技术新突破:多模态与语音大模型重塑智能交互
  • VTK的两种显示刷新方式
  • 06-Spring 中的事件驱动机制
  • JAVA学习小记之IO流04--转换流篇
  • EasyExcel 数据字典转换器实战:注解驱动设计
  • Django4.0的快速查询以及分页
  • Flink SQL-Client Kafka connector
  • Uni-app 项目 PDF 批注插件库在线版 API 示例教程
  • Ceph异地数据同步之-RBD异地同步复制(上)
  • 每日一题(小白)ASCLL娱乐篇5
  • ARM架构+CODESYS:解锁嵌入式边缘计算的实时控制新范式
  • MIT6.828 Lab3-2 Print a page table (easy)
  • 大数据学习(98)-数据治理
  • 预测分析(二):基于机器学习的数值预测
  • 【大模型基础_毛玉仁】6.3 知识检索
  • API接口调用
  • 通信算法之256: 无人机Remote ID(远程识别)
  • adc推荐,单通道,双极性采集
  • 最近常用 python 记录
  • 环境数据综合分析系统
  • 贤小二c#版Yolov5 yolov8 yolov10 yolov11自动标注工具 + 免python环境 GPU一键训练包
  • 贴片加工SMT厂核心工艺解析
  • 码界奇缘 Java 觉醒 第二章 变量迷城