页面json 格式化+颜色高亮

简介: 背景 应答为json,为了更好的展示在前端页面,需要对其格式化加颜色高亮   效果图   步骤 js中添加 function output(inp) { document.

背景

应答为json,为了更好的展示在前端页面,需要对其格式化加颜色高亮

 

效果图

 

步骤

js中添加

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    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>';
    });
}

var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
var str = JSON.stringify(obj, undefined, 4);

output(str);
output(syntaxHighlight(str));

 

css中添加

pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }

 

参考资料

https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript

虽千万人,吾往矣!
目录
打赏
0
0
0
0
3
分享
相关文章
JSON 数据格式化方法
JSON 数据格式化方法
163 3
json字符串CSS格式化
完成以上步骤后,你便能在网页中看到格式化后的JSON数据,它们将按照CSS定义的样式进行展示,使数据更易于阅读和理解。通过有效地结合JSON和CSS,你可以创建出更加丰富且易于交互的网页内容。
240 64
js如何格式化一个JSON对象?
js如何格式化一个JSON对象?
157 3
json字符串CSS格式化
json字符串CSS格式化
95 5
【Azure Event Hub】Event Hub的Process Data页面无法通过JSON格式预览数据
【Azure Event Hub】Event Hub的Process Data页面无法通过JSON格式预览数据
|
6月前
|
Sublime Json 格式化
Sublime Json 格式化
84 0
vue 格式化展示json(含彩色样式)
vue 格式化展示json(含彩色样式)
530 1
Notepad++怎么格式化json文件?
Notepad++怎么格式化json文件?
使用CRXjs、Vite、Vue 开发 Chrome 多页面插件,手动配置 vite.config.ts 和 manifest.json 文件
使用CRXjs、Vite、Vue 开发 Chrome 多页面插件,手动配置 vite.config.ts 和 manifest.json 文件
295 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等