当前位置:网站首页>使用<pre>和JSON.stringify处理网页展示JSON的格式
使用<pre>和JSON.stringify处理网页展示JSON的格式
2022-07-17 08:55:00 【裕东方】
前言
最近有一个项目,需要在前端展示一个元数据(Metadata)的详细信息,以JSON格式从后端返回,将JSON对象处理为字符串在前端展示时,发现它的格式非常奇怪,所有的字段挤在一起,且部分字段过长,严重影响阅读,如下:
{ "key1": value1, "key2": value2, "key3": value3 }预期的显示应该是有换行的:
{
"key1": value1,
"key2": value2,
"key3": value3
}本文解决此类JSON在前端显示时的格式问题。
方法
第一步:对后端传来的JSON对象进行序列化,如下:
Obj = JSON.stringify(JSON对象, null, 4);具体的解释在:JavaScript JSON.stringify() | 菜鸟教程 (runoob.com)
其中,第一个参数为JSON对象,第二个参数可以暂时不管,第三个参数代表JSON每个层级缩进的字符数,也可以为换行符、制表符等。
第二步:使用<pre>标签包装序列化后的对象
如果只进行到步骤1,就将对象在前端页面上展示,那么所有的字段仍然会贴在一起,没有层次。
为了解决这个问题,需要用<pre>标签,包装该对象,如下:
<pre>
{Obj}
</pre><pre> 标签可定义预格式化的文本,且被包围在 <pre> 标签 元素中的文本通常会保留空格和换行符。
参考资料
javascript - How can I beautify JSON programmatically? - Stack Overflow
边栏推荐
- Collation of exercises of shallow neural networks in the third week of in-depth study
- [handwritten numeral recognition] handwritten numeral recognition based on lenet network with matlab code
- How to write a string field in MySQL if its value is not empty?
- RPA相关知识点整理
- 为什么别人游戏里的特效都非常柔和
- 【手写数字识别】基于Lenet网络实现手写数字识别附matlab代码
- Redis
- 【Port 3000 is already in use,3000端口被占用问题解决方法】
- [regression prediction] lithium ion battery life prediction based on particle filter with matlab code
- pygame中display模块
猜你喜欢

LeetCode 0116. Populate the next right node pointer for each node

LabVIEW用了多线程,程序是不是会跑的更快些

Magic Usage of mongodb $symbol +mongo data type

自定义MVC原理及简单实现

New application of arm computing, illegal fishing "catch all"

分布式事务-最大努力通知方案

如何在 Authing 上快速实现 Zadig 单点登录?

AuthTalk 第一期预告 | 全面拆解多租户解决方案

【手写数字识别】基于Lenet网络实现手写数字识别附matlab代码

Scratch reverse order output electronic society graphical programming scratch grade examination level 4 true questions and answers analysis June 2022
随机推荐
ARM计算新应用,违规垂钓“一网打尽”
Collation of RPA related knowledge points
Distributed transaction reliable message final consistency solution
It's also very difficult. I'm not only tired of writing by myself
QR decomposition for matrix inversion -- C engineering implementation
2022t elevator repair examination question bank and answers
结构体和联合体的区别与联系
LeetCode 0115. Different subsequences
WPF 3D application building (Foundation)
What is memory overflow
为什么别人游戏里的特效都非常柔和
Redis
Magic Usage of mongodb $symbol +mongo data type
Cbcgpedit control used by BCG
Example description of alternative writing of instanceof
TP5微信提现 商家转账到零钱(复制皆可用)
Block 的分类
[face recognition] face recognition based on histogram histogram with matlab code
对ogg用户进行加密
46. IO model