Sometimes we need to display the JSON data directly on the page (such as the item where the interface test is done, and the result of the interface return is directly displayed), but if the string is displayed directly, it is not convenient to view. Need to format.
Solution:In fact, json.stringify itself can format JSON. The specific usage is:
Json.stringify (Res, NULL, 2); // Res is the object of JSON, 2 is spacing
If the effect is better, add the formatted code and style:
js code: Function SyntaxHighlight (json) {if (typeof json! = 'String') {json = json.stringify (json, undefined, 2);} json = json.replace (/&/g, '&'). replace (// </g, '<<'). Replace (/>/g, '>'); Return json.replace (/(//(/u [a-za-z0-9] {4} | // [^u ] | [^//])*(/s*:)? |/b (true | false | null)/b |-?/d+(?: /./ d*)? (?: [ee] [ +/-]?/d+)?)/G, Function (MATCH) {Var CLS = 'Number'; if (/^/.test (match)) {if (/: $/.test (match)) { CLS = 'Key';} Else {class = 'String';}} Else if (/True| False/.test (match)) {cls = 'boolean'; ) {cls = 'null';} Return '<span class =' + class + '>' + match + '</span>';});};}Style code:
<Style> Pre {outline: 1px solid #ccc; padding: 5px; margin: 5px;} .string {color: green;}. Number {color: darkorange;} .Boolean {color: block;}. l {color: Magenta;} .Key {color: red;} </style>html code:
<pre id = result> </pre>
Code:
$ ('#Result'). html (SyntaxHighlight (res));Effect:
The above is the method of displaying JSON data to display JSON data in HTML. I hope it will be helpful to everyone. If you have any questions, please leave me a message. Xiaobian will reply to everyone in time. Thank you very much for your support for the VEVB Wulin website!