一、准备一段测试用的Json文本

{
    "age" : 12,
    "name" : "zhiyuan",
    "gender" : "male",
    "skill" : ["J a v a","C","J S","Py th on"]
}

二、去除除value值中的空白字符之外的所有空白字符

function clearEmpty(){
    var json = document.getElementById("content").value;
    console.log(json);
    let str = json.replace("\r\n","");
    let newStr = str.trim().replace(/\s*\[\s*/g,"\[").replace(/\s*\]\s*/g,"\]").replace(/\s*\{\s*/g,"\{").replace(/\s*\}\s*/g,"\}").replace(/"\s*:\s*"/g,'":"').replace(/"\s*:\s*/g,'":').replace(/"\s*,\s*/g,'",').replace(/,\s*"/g,',"').replace(/]\s*,\s*/g,"],");
    console.log(newStr);
    document.getElementById("new-content").innerText = newStr;
}

三、写一个难看的页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Json文本格式压缩</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family:微软雅黑,sans-serif;
    }
    .container{
        width: 100%;
        height:auto;
        background-color:#f8f8f8;
        padding:20px;
        position: relative;
    }
    #content,#new-content{
        width: 100%;
        height:300px;
        background-color: #ffffff;
        color:#666;
        font-size:14px;
        outline:none;
        border:1px solid #1DB69A;
        border-radius:10px;
        padding:20px;
    }
    button{
        background-color:#FFFFFF;
        color: #1DB69A;
        height: 50px;
        width: 150px;
        font-size: 18px;
        outline:none;
        border:1px solid #1DB69A;
        cursor: pointer;
        border-radius:50px;
        margin:20px;
        position: absolute;
        right:20px;
        top:250px;
    }
    button:hover{
        background-color:#1DB69A;
        color: #FFFFFF;
    }
    button:focus{
        background-color:#009688;
        color:#FFFFFF;
    }
    .line{
        width:980px;
        margin:20px auto;
        font-size:20px;
        font-weight:bold;
        border-left:300px solid #1DB69A;
        border-right:300px solid #1DB69A;
        line-height: 2px;
        text-align: center;
        color: #1DB69A;
    }
</style>
<body>
    <div class="container">
        <div class="line">请将json格式文本粘贴到文本框中</div>
        <textarea name="content" cols="50" rows="20" id="content"></textarea>
        <button onclick="clearEmpty()">去除所有空格</button>
        <div class="line">下面将生成去除空格的Json文本</div>
        <textarea name="new-content" id="new-content" cols="50" rows="20" disabled></textarea>
    </div>
</body>
</html>

四、测试一下效果

原文作者:絷缘
作者邮箱:zhiyuanworkemail@163.com
原文地址:https://zhiyuandnc.github.io/ZeuH4X3iy/
版权声明:本文为博主原创文章,转载请注明原文链接作者信息