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
1. Create a scheduling task instruction crontab -...
Table of contents Actual combat process Let's...
Hello everyone! I am Mr. Tony who only talks abou...
The first step is to unzip the compressed package...
When creating a time field DEFAULT CURRENT_TIMEST...
Preface: In project development, some business ta...
This article uses examples to illustrate the pitf...
BFC BFC: Block Formatting Context BFC layout rule...
Preface Students who learn JavaScript know that A...
Table of contents 1. We must ensure that the vue/...
illustrate DML (Data Manipulation Language) refer...
The storage size and range of each floating point...
Table of contents Why use gzip compression? nginx...
1. Introduction I wrote an article before: The pr...
Result: html <nav id="nav-1"> <...