This example describes the JavaScript formatted JSON display method. Share to everyone for your reference. The specific analysis is as follows:
Format a JSON object or JSON string to easily restrict on a Web page
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.newlineaftercol Onifbeforebraceorbracket = = True)?
True:false; Use a spaces 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.stri
Ngify (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, ' \r\n$1\r\n ');
Add newline before and after square brackets reg =/([\[\]])/g; JSON = Json.replace (Reg, ' \r\n$1\r\n');
Add newline after comma reg =/(\,)/g;
JSON = Json.replace (Reg, ' $1\r\n ');
Remove multiple Newlines reg =/(\r\n\r\n)/g;
JSON = Json.replace (Reg, ' \ r \ n ');
Remove newlines before commas reg =/\r\n\,/g;
JSON = Json.replace (Reg, ', ');
Optional formatting. if (!options.newlineaftercolonifbeforebraceorbracket) {reg =/\:\r\n\{/g;
JSON = Json.replace (Reg, ': {');
reg =/\:\r\n\[/g;
JSON = Json.replace (Reg, ': [');
} if (Options.spaceaftercolon) {reg =/\:/g;
JSON = Json.replace (Reg, ': ');
$.each (Json.split (' \ r \ n '), 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 + ' \ r \ n ';
Pad + + indent;
});
return formatted; };
Friends who are interested in JSON formatting can also refer to the online tools:
JSON Code Tool
I hope this article will help you with your JavaScript programming.