博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
js/javascript format json(js/javascript 格式化json字符串)
阅读量:4962 次
发布时间:2019-06-12

本文共 6796 字,大约阅读时间需要 22 分钟。

// format json obj stringfunction format_json(txt, compress) {    var indentChar = '    ';    if (/^\s*$/.test(txt)) {        //alert('txt is empty');           return '';    }    try {        var data = eval('(' + txt + ')');        txt = txt.replace(new RegExp("\"{","gm"), "{").replace(new RegExp("}\"","gm"), "}");        txt = txt.replace(new RegExp("\\\\\\\"","gm"), "\"");        txt = txt.replace(new RegExp("\\\\\\\"","gm"), "\"");        txt = txt.replace(new RegExp("\\\\\\\"","gm"), "\"");        txt = txt.replace(new RegExp(" ","gm"), "");//        console.log(txt);        data = eval('(' + txt + ')');    } catch (e) {        //alert('txt format error: '+e.description,'err');           return txt;    }    ;    var draw = [], last = false, This = this, line = compress ? ''            : '
', nodeCount = 0, maxDepth = 0; var notify = function(name, value, isLast, indent, formObj) { if (indent == 0) { //draw.push('
'); } nodeCount++; for (var i = 0, tab = ''; i < indent; i++) tab += indentChar; tab = compress ? '' : tab; maxDepth = ++indent; if (value && value.constructor == Array) { draw.push(tab + (formObj ? ('"' + name + '":') : '') + '[' + line); for (var i = 0; i < value.length; i++) notify(i, value[i], i == value.length - 1, indent, false); draw.push(tab + ']' + (isLast ? line : (',' + line))); } else if (value && typeof value == 'object') { draw.push(tab + (formObj ? ('"' + name + '":') : '') + '{' + line); var len = 0, i = 0; for ( var key in value) len++; for ( var key in value) notify(key, value[key], ++i == len, indent, true); draw.push(tab + '}' + (isLast ? line : (',' + line))); } else { if (typeof value == 'string') value = '"' + value + '"'; draw.push(tab + (formObj ? ('"' + name + '":') : '') + value + (isLast ? '' : ',') + line); } ; }; var isLast = true, indent = 0; notify('', data, isLast, indent, false); return draw.join('');}function addIndentBlank(indent) { indentChar = '    '; var ret = ""; for (var i = 0; i < indent; i++) { ret += indentChar; } return ret;}// format all stringfunction format_str(txt) { if (/^\s*$/.test(txt)) { //alert('txt is empty'); return ''; } try { //var data = eval('(' + txt + ')'); txt = txt.replace(new RegExp("\"{","gm"), "{").replace(new RegExp("}\"","gm"), "}"); // "{->{ }"->} txt = txt.replace(new RegExp("\\\\\\\"","gm"), "\""); // \"->" txt = txt.replace(new RegExp("\\\\\\\"","gm"), "\""); txt = txt.replace(new RegExp("\\\\\\\"","gm"), "\""); txt = txt.replace(new RegExp("\\\\\\\\r","gm"), "\\r"); txt = txt.replace(new RegExp("\\\\\\\\n","gm"), "\\n"); txt = txt.replace(new RegExp("\\\\\\\\r","gm"), "\\r"); txt = txt.replace(new RegExp("\\\\\\\\n","gm"), "\\n"); txt = txt.replace(new RegExp("\\\\\\\\r","gm"), "\\r"); txt = txt.replace(new RegExp("\\\\\\\\n","gm"), "\\n"); //txt = txt.replace(new RegExp(" ","gm"), ""); var draw = []; var line = ""; var indent = 0; var quoteCount = 0; var quoteOddEven = 0; // Even count quote(") to deal, Odd is string var containLeftBrace = false; var preChar = ''; var nextChar = ''; for (var i = 0; i < txt.length; i++) { current = txt.charAt(i); try { nextChar = txt.charAt(i + 1); } catch (e) { console.log(e); } switch (current) { case '{': containLeftBrace = true; case '[': { if (preChar == '\"') { draw.push(current); break; } if (quoteOddEven == 0) { ++indent; draw.push(current); draw.push(line); draw.push(addIndentBlank(indent)); break; } else { draw.push(current); break; } } case '}': case ']': { if (nextChar == '\"') { draw.push(current); break; } if (quoteOddEven == 0) { --indent; draw.push(line); draw.push(addIndentBlank(indent)); draw.push(current); break; } else { draw.push(current); break; } } case ',': { if (quoteOddEven == 0 && quoteCount > 0 && containLeftBrace) { draw.push(current); draw.push(line); draw.push(addIndentBlank(indent)); break; } else { draw.push(current); break; } } case '\\': { try { next1 = txt.charAt(i+1); next2 = txt.charAt(i+2); next3 = txt.charAt(i+3);// console.log(current + next1 + next2 + next3); if ((next1 + "") == "r" && (current + next1 + next2 + next3) == "\\r\\n") { draw.push(line); draw.push(addIndentBlank(indent + 1)); i = i+3; } } catch(e) { console.log(e); } break; } case '\"': { quoteCount = quoteCount + 1; quoteOddEven = (quoteOddEven + 1) % 2; draw.push(current); break; } default: { draw.push(current); } } preChar = current; }// console.log('draw: ' + draw.join('')); } catch (e) {// alert('txt format error: '+e,'err'); return txt; } ; return draw.join('');}

 

转载于:https://www.cnblogs.com/cobble19/p/6256156.html

你可能感兴趣的文章
数据结构学习记录_2019.02.23
查看>>
使用Android Studio来阅读Android源码
查看>>
java 实现word文档在线预览
查看>>
CTSC/APIO2018 帝都一周游
查看>>
如何实现数据库实体生成工具
查看>>
中兴2018届应届生在线编程测验0829 数学家排成平行四边形问题
查看>>
java中的全局变量如何实现?ThreadLocal~
查看>>
MQ异步同步搜索引擎ElasticSearch数据踩坑
查看>>
CPUID
查看>>
页码数求0到9共有多少个
查看>>
通过编码设定 ObjectDataSource 参数值6
查看>>
Json格式获取接口返回的值
查看>>
AppCan认为,移动APP开发不是技术活
查看>>
curl
查看>>
协同过滤算法
查看>>
矩阵快速幂 模板
查看>>
[MySQL] AUTO_INCREMENT lock Handing in InnoDB
查看>>
动手动脑
查看>>
创建图像映射
查看>>
Django后端向前端直接传html语言防止转义的方法(2种)
查看>>