js string format json

1. The three parameters of JSON.stringify

var json = {"@odata.context":"$metadata#AddTableOne_466281s","value":[{"NAME":"李四","BIRTHDAY":"2018-10-03T11:33:50+08:00","AGE":"0","ID":"111111"}]}
JSON.stringify(json, null, "\t")
View Code

2.

<! DOCTYPE HTML > 
< HTML lang = "EN" > 
< head > 
    < Meta charset = "UTF-. 8" > 
    < title > JS format JSON </ title > 
    < Script > 
    var formatJson =  function (JSON) {
         var outStr =  '' ,      // JSON converted string 
            padIdx =  0 ,          // whether to increase or decrease after the new line identification PADDING 
            Space =  '    ';   //4个空格符
        if (typeof json !== 'string') {
            json = JSON.stringify(json);
        }
        debugger
        json = json.replace(/([\{\}\[\]])/g, '\r\n$1\r\n')          
                    .replace(/(\,)/g, '$1\r\n')
                    .replace(/(\r\n\r\n)/g, '\r\n'); 
       (json.split('\r\n')).forEach(function (node, index) {
            var indent = 0,
                padding = '';
            if (node.match(/[\{\[]/)){
              indent = 1;
            }else if (node.match(/[\}\]]/)){
              padIdx = padIdx !== 0 ? --padIdx : padIdx;
            } The else { 
              indent =  0 ; 
            }     
            for ( var I =  0 ; I < padIdx; I ++ ) { 
              padding + = Space; 
            }     
            outStr + = padding + Node +  ' \ R & lt \ n- ' ; 
            padIdx + = indent; 
        } ); 
        return outStr; 
    }; 
    // reference to exemplary portion 
    //var originalJson = { 'name': 'CCY', 'Age': 18 is, 'info': [{ 'address': 'Wuhan'}, { 'Interest': 'playCards'}]}; 
    var showJson =  function ( ) {
         var originalJson = document.getElementById ( ' inputJson ' ) .Value; 
        the console.log (originalJson); 
        // (2) function call formatJson the format json format 
        var resultJson = formatJson (originalJson); 
        document.getElementById ( ' OUT ' ) .innerHTML = resultJson; 
    } 
</ Script > 
</head>
<body>
    <span style="position:absolute;left:0px;top:20px;font-size: 20px;font-family: '微软雅黑';color: #2F4F4F;">输入json</span>
    <textarea style="position:absolute;left:0px;top:80px;width:40%;height:80%;" cols="50" rows="20" id="inputJson"></textarea>
    <span style="position:absolute;left:55%;top:20px;font-size: 20px;font-family: '微软雅黑';color: #2F4F4F;">查看结果</span>
    <textarea style="position:absolute;left:55%;top:80px;width:40%;height:80%;display: " id="out"></textarea>
    <div style="position:absolute;left:45%;top:12%;width:6%;height:4%;">
    <input type="button" value="提交" onclick="showJson();">
    </div>
</body>
</html>
View Code

 

Guess you like

Origin www.cnblogs.com/justSmile2/p/11279951.html