Background:
Sometimes we need to display the JSON data directly on the page (for example, in an interface test project, we need to show the results of the interface return directly), but if the string is displayed directly, it is not convenient to view. Need to format it.
Solution:
In fact, json.stringify itself can be formatted JSON, the specific usage is:
NULL // Res is the object to be JSON, 2 is spacing
If you want to look better, add the formatted code and style:
JS Code:
functionSyntaxhighlight (JSON) {if(typeofJSON! = ' string ') {JSON= Json.stringify (JSON, Undefined, 2); } JSON= Json.replace (/&/g, ' & '). Replace (/</g, ' < '). Replace (/>/g, ' > ')); returnJson.replace (/("(\\u[a-za-z0-9]{4}|\\[^u]|[ ^\\ "]) *" (\s*:)? | \b (True|false|null) \b|-?\d+ (?: \. \d*)? (?: [ee][+\-]?\d+)?) /g,function(match) {varCLS = ' number '; if(/^"/. Test (Match)) { if(/:$/. Test (Match)) {CLS= ' key '; } Else{CLS= ' String '; } } Else if(/true|false/. Test (Match)) {CLS= ' Boolean '; } Else if(/null/. Test (Match)) {CLS= ' null '; } return' <span class= ' + cls + ' "> ' + match + ' </span> '; });}
Style code:
<style> Pre{Outline:1px solid #ccc;padding:5px;margin:5px; }. String{Color:Green; }. number{Color:Darkorange; }. Boolean{Color:Blue; }. Null{Color:Magenta; }. Key{Color:Red; }</style>
HTML code:
<id= "result"></pre>
Calling code:
$ (' #result '). HTML (syntaxhighlight (res));
Effect:
Displaying JSON in an HTML page