Displaying JSON in an HTML page

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.