luinstein 发表于 2012-12-13 23:19:06

json format:json数据格式化


json数据格式化(json format)实现方法,直接上代码<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">


<body>
<div id="show_ajax"></div>

<textarea cols="100" rows="5" id="show_ajax2"></textarea>

<script>
/*
json-format v.1.1
http://github.com/phoboslab/json-format

Released under MIT license:
http://www.opensource.org/licenses/mit-license.php
*/

(function(window) {
var p = [],
push = function( m ) { return '\\' + p.push( m ) + '\\'; },
pop = function( m, i ) { return p },
tabs = function( count ) { return new Array( count + 1 ).join( '\t' ); };

window.JSONFormat = function( json ) {
p = [];
var out = "",
indent = 0;

// Extract backslashes and strings
json = json
.replace( /\\./g, push )
.replace( /(".*?"|'.*?')/g, push )
.replace( /\s+/, '' );

// Indent and insert newlines
for( var i = 0; i < json.length; i++ ) {
var c = json.charAt(i);

switch(c) {
case '{':
case '[':
out += c + "\n" + tabs(++indent);
break;
case '}':
case ']':
out += "\n" + tabs(--indent) + c;
break;
case ',':
out += ",\n" + tabs(indent);
break;
case ':':
out += ": ";
break;
default:
out += c;
break;
}
}

// Strip whitespace from numeric arrays and put backslashes
// and strings back in
out = out
.replace( /\[[\d,\s]+?\]/g, function(m){ return m.replace(/\s/g,''); } )
.replace( /\\(\d+)\\/g, pop ) // strings
.replace( /\\(\d+)\\/g, pop ); // backslashes in strings

return out;
};
})(window);


var someJSONString= '{ "count": 5, "time_interval": 5 }'
var formattedJSONString = JSONFormat( someJSONString );

document.getElementById("show_ajax2").innerHTML =formattedJSONString;

</script>
</body>
</html>

页: [1]
查看完整版本: json format:json数据格式化