background: Sometimes we need to display json data directly on the page (for example, when doing an interface testing project, we need to display the results returned by the interface directly), but if the string is displayed directly, it is not convenient to view. Needs formatting. Solution: In fact, JSON.stringify itself can format JSON. The specific usage is: JSON.stringify(res, null, 2); //res is the object to be JSONified, 2 is spacing If you want a better effect, you need to add formatting 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 { 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: <pre id="result"> </pre> Calling code: $('#result').html(syntaxHighlight(res)); Effect: The above is the method I introduced to you to display JSON data in HTML. I hope it will be helpful to you. If you have any questions, please leave me a message and I will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website! |
<<: Solution to occasional crash of positioning background service on Linux
>>: Let's talk briefly about the changes in setup in vue3.0 sfc
The specific code for sending emoticons in the vu...
When laying out the page, in order to give users ...
Table of contents Simple Factory Factory Method S...
Chinese Tutorial https://www.ncnynl.com/category/...
Ubuntu 20.04 has been released, bringing many new...
In the past two days, I have been very troubled t...
Moreover, an article website built with a blog pro...
I have been learning porters recently. I feel lik...
Copy code The code is as follows: <!DOCTYPE ht...
Transaction A transaction is a basic unit of busi...
Background requirements: The ERP system needs to ...
HTML5 adds more semantic tags, such as header, fo...
Downloaded the unzipped version of mysql-5.6.37-w...
environment Linux 3.10.0-693.el7.x86_64 Docker ve...
This article example shares the specific code of ...