首页 > 编程知识 正文

前端json格式化插件,js json格式化显示

时间:2023-05-05 19:18:54 阅读:158211 作者:1773

1 .故事前景:后端向前端返回一系列json字符串。 前端需要进行格式化处理,让用户看起来更美。

2 .效果演示:

3 .实现代码: doctypehtmlhtmllang=' en ' headmetacharset=' utf-8 ' metaname=' viewport ' content=' width=device-wice initial-scale=1.0 ' meta http-equiv=' x-ua-compatible ' content=' ie=edge ' title JSON数据格式/title style /*。 width: 40%; height: 70vh; outline: none; padding: 5px; (/*方法2 )自定义高亮样式(/#JSONpre )浮点:左; width: 40%; height: 70vh; outline: 1px solid #ccc; padding: 5px; overflow :滚动; } .string { color: green; } .number { color: darkorange; } .boolean { color: blue; } .null { color: magenta; } .key { color: red; }/style/headbodytextareaid=' JSON textarea ' readonly/textareapreid=' JSON pre '/pre/bodyscriptsrc='./jquery ssssteare ' sex': '男人',' Age':25,' hobby':[ ','篮球','跑步',' sex': '男人',' age ' :20 //方法1:textarea JSON.stringifyfunctionparse1(str ) { return JSON.stringify } JSON.parse (str ),null,'t '; }$('#JSONtextarea ' ).text parse1(data ); //方法2:pre JSON.stringifyfunctionparse2(str )//缩进两个空格的str=JSON.stringify(JSON.parse ) str ),null,2 str=str.replace(/g,' amp; '.replace(/g,' lt; '.replace(/g,' gt; ' ); returnstr.replace(/) ((() (a-za-z0-9 ) )|(() ) ) ) () ) ) (s () ) )| b (true ) d (?.d*? (?[eE][ -]? d (? (/g,function ) match ) { var cls='number '; if(/^ )/.test(match ) (if )/:$/.test ) match ) ) { cls='key '; } else { cls='string '; }elseif(/true|false/.test ) match ) ) { cls='boolean '; }elseif(/null/.test ) ) { cls='null '; } return ' span class=" " cls " " match "/span "; ); }$('#JSONpre ' ).html ) parse2(data ); /script/html注:上面的代码引入了jquery以便于dom操作。 自己导入jquery就可以直接演示了。

4 .参考资料: JSON.stringify(-JavaScript|MDN

在html页面上显示JSON

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。