Js格式化json字符串

摘要:
假:真;//开始信息…if(typeofjson!==‘string'){//确保使用JSONasastringson=JSON.stringfy(JSON);}否则{//isalreadyastring,soparseandre stringifyinordertoremoveextrawhitespacejson=JSON.parse(JSON);JSON=JSON.stringify(JSON);}//在当前bracesreg=/([{}])/g之前添加新行;json=json。replace(reg,“$1”);//在方括号reg=/([[]])/g之前添加换行符;json=json。replace(reg,“$1”);//addnewlineaftercmmareg=/(\,)/g;json=json。replace(reg,“$1”);//removemultiplenewlinesreg=/()/g;json=json。replace(reg,'');//removewlinesbeforecommasreg=/\,/g;json=json。replace(reg,',');//optionalformating…if(!==0){pad-=1;}}否则{indent=0;}对于(i=0;i˂pad;i++){padding+=padding;}格式化+=填充+节点+“”;pad+=缩进;});returnformated;};varstr1='{“name”:“xiaol”,“sex”:“man”}';formatJson(str1){“name”:“xiaol”,“sex”:“man”}
var formatJson = function(json, options) {
    var reg = null,
        formatted = '',
        pad = 0,
        PADDING = '    '; // one can also use '	' or a different number of spaces
  
    // optional settings
    options = options || {};
    // remove newline where '{' or '[' follows ':'
    options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
    // use a space after a colon
    options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
  
    // begin formatting...
    if (typeof json !== 'string') {
        // make sure we start with the JSON as a string
        json = JSON.stringify(json);
    } else {
        // is already a string, so parse and re-stringify in order to remove extra whitespace
        json = JSON.parse(json);
        json = JSON.stringify(json);
    }
  
    // add newline before and after curly braces
    reg = /([{}])/g;
    json = json.replace(reg, '
$1
');
  
    // add newline before and after square brackets
    reg = /([[]])/g;
    json = json.replace(reg, '
$1
');
  
    // add newline after comma
    reg = /(\,)/g;
    json = json.replace(reg, '$1
');
  
    // remove multiple newlines
    reg = /(

)/g;
    json = json.replace(reg, '
');
  
    // remove newlines before commas
    reg = /
\,/g;
    json = json.replace(reg, ',');
  
    // optional formatting...
    if (!options.newlineAfterColonIfBeforeBraceOrBracket) {        
        reg = /:
{/g;
        json = json.replace(reg, ':{');
        reg = /:
[/g;
        json = json.replace(reg, ':[');
    }
    if (options.spaceAfterColon) {         
        reg = /:/g;
        json = json.replace(reg, ': ');
    }
  
    $.each(json.split('
'), function(index, node) {
        var i = 0,
            indent = 0,
            padding = '';
  
        if (node.match(/{$/) || node.match(/[$/)) {
            indent = 1;
        } else if (node.match(/}/) || node.match(/]/)) {
            if (pad !== 0) {
                pad -= 1;
            }
        } else {
            indent = 0;
        }
  
        for (i = 0; i < pad; i++) {
            padding += PADDING;
        }
  
        formatted += padding + node + '
';
        pad += indent;
    });
  
    return formatted;
};

var str1 = '{ "name": "xiaol", "sex": "man" }'; 

formatJson(str1)

{
  "name": "xiaol",
  "sex": "man"
}

免责声明:文章转载自《Js格式化json字符串》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇python3中argparse模块详解postgresql 行列互转函数下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

Pycharm Debug功能详解

左键单击代码编辑区域中的行号以在调试模式下运行代码:单击左上角工具栏上的调试图标(bug图)。方法2:在调试模式下运行后,1。代码编辑区域中的蓝色条是当前程序运行的位置,即c=add(a)应该运行,但尚未运行。2.代码编辑区域中的深红色条是当前程序设置的所有断点行。3.左下方是程序堆栈,进入fun()函数。4.右下方是可变显示区域1。跳转到当前断点(在断点之...

PLSQL操作Oracle创建用户和表(含创建用户名和密码)

1》 打开PLSQL,填写用户名和密码,为数据库选择ORCL2,成功登录后可以在界面顶部看到以下信息system@ORCL这意味着用户系统处于登录状态。菜单栏中的会话可以登录和注销。...

通过 java的 esl 连接 freeswitch

--所有ip都能通过esl连接到freeswitch--˃4.reloadmod_event_socket5.通过java的esl连接fs服务器三、报错[WARNING]mod_event_socket.c:2641IPx.x.x.xRejectedbyacl"loopback.auto"四、以前版本按照步骤二操作完就可以了,现在报错了。世界变化的太快。--...

如何让 ESLint 同时检测 js 和 ts

但是ESLint默认使用Espree作为其解析器,在某些情况下不支持TypeScript语法。另外,TypeScript是JavaScript超集,有更多的语法,ESLint本身提供的规则无法满足。ESLint有一项overrides的配置,可以为某个文件或者某组文件进行覆盖配置。因此,我们可以设置ts文件使用@typescript-eslint/parse...

docker默认网段和主机网段冲突解决

一、docker默认网卡docker0172.17.0.0可能会与主机冲突,这时候需要修改docker默认分配的网段1、修改/etc/docker/daemon.json文件,加入以下代码{"default-address-pools":[{"base":"172.100.0.0/16","size":24}]}其中上面的172.100.0.0/16是自定义...

使用代理软件之后其他软件不能联网的解决方法

可能是代理软件打开后,代理端口被自动修改,但我们没有正常关闭代理软件。代理端口没有在此代理模式下切换回来,因此我们仍然使用全局代理,但没有打开代理软件。此时,网络无法正常连接。此时,其他软件可以正常使用,但使用全局代理的速度非常慢。除非您需要FQ,否则不建议对通用软件使用全局代理。...