JavaScript 格式化显示JSON


先说结论,使用JSON.stringify方法 第三个参数参数格式化显示,用pre标签保留空格和换行符

JavaScript:
const jsonString = JSON.stringify(testjson, null, '\t');
Html:
<pre> jsonString <pre>

1 过程

近期需要手搓一个界面,通过restful
API拿到一个json数据,希望像这样显示在界面上,方便检查复制。

{
		name: "哈哈",
		age: 23,
		region: 'cn-northwest-1'
}


准备用一个p标签来显示

<p>data<p>

1 直接将Object传入出来一个这个

[object Object]

2 转成JSON string格式化一下:

const jsonString = JSON.stringify(testjson)

显示出这个

{"name":"哈哈","age":23,"region":"cn-northwest-1"}

3 去MDN上找JSON.stringify 的方法
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

发现第三个参数可以格式化显示。

const jsonString = JSON.stringify(testjson, null, '\t')

在调试窗口打印格式化输出都正常了,但实际上放到p标签中显示出来又变成这样了

{ "name": "哈哈", "age": 23, "region": "cn-northwest-1" }

4 找了半天终于发现是p标签用错了,这里应该使用pre标签
pre 元素可定义预格式化的文本。被包围在 pre 元素中的文本通常会保留空格和换行符。而文本也会呈现为等宽字体。
标签的一个常见应用就是用来表示计算机的源代码。
换成pre标签后 就可以保留正常显示JSON.stringify(testjson, null, ‘\t’) 格式化输出的字符串了

<pre>data<pre>

2 测试代码

测试代码,本地保存为html文件即可测试

<div id="list">
	<p id="title">JSON显示测试</p>
</div>

<script>
	const testjson = {
		name: "哈哈",
		age: 23,
		region: 'cn-northwest-1',
	}
	const list = document.getElementById('list');
  const object = document.createElement('pre');
	const JsonString = document.createElement('pre');
	const JsonStringFormat = document.createElement('pre');
	const JsonStringFormatPLabel = document.createElement('p');

	setTimeout(() => {
		object.innerHTML = `${testjson}`;
		list.appendChild(object);
	},1000);
	
	setTimeout(() => {
		JsonString.innerHTML = `${JSON.stringify(testjson)}`;
		list.appendChild(JsonString);
	},1500);
	
	setTimeout(() => {
		JsonStringFormat.innerHTML = JSON.stringify(testjson, null, '\t');
		list.appendChild(JsonStringFormat);
	},2000);
	
	setTimeout(() => {
		JsonStringFormatPLabel.innerHTML = JSON.stringify(testjson, null, '\t');
		list.appendChild(JsonStringFormatPLabel);
	},2000);
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章