//对json字符串进行格式化 //options可以去掉 var formatJson = function (json, options) { var reg = null, formatted = '', pad = 0, PADDING = ' '; // one can also use '\t' 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... // make sure we start with the JSON as a string if (typeof json !== 'string') { json = JSON.stringify(json); } // parse and stringify in order to remove extra whitespace json = JSON.parse(json); json = JSON.stringify(json);
JS中json字符串进行格式化
最新推荐文章于 2024-07-26 02:49:06 发布
该博客介绍了如何在JavaScript中对JSON字符串进行格式化,包括添加换行符、空格,并提供了自定义选项来调整格式。通过JSON.parse和JSON.stringify去除额外的空白,然后使用正则表达式对括号、逗号等进行替换,实现格式化的JSON字符串。
摘要由CSDN通过智能技术生成