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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章