把下面的JSON數據顯示在HTML頁面中:
arr = [{
id: 1,
desc: "This is the description of the first object."
}, {
id: 2,
desc: "This is the description of the second object."
}, {
id: 3,
desc: "This is the description of the third object. Now, I'm going to repeat the description of this value.This is the description of the third objectThis is the description of the third objectThis is the description of the third object"
}, {
id: 4,
desc: "This is the description of the third object."
}]
實現方式:
HTML:
<pre>
<code id="show"></code>
</pre>
JS:
var show = document.getElementById('show'),
newData = JSON.stringify(arr, null, 4);
show.innerHTML = newData;
結果圖:
demo.png
說明:
pre標簽(w3school)
pre元素可定義預格式化的文本。被包圍在pre元素中的文本通常會保留空格和換行符。而文本也會呈現為等寬字體。
pre標簽一個常見的應用就是用來表示計算機的源代碼。
可以導致段落斷開的標簽(例如標題、<p>、<address>標簽)絕不能包含在pre定義的塊里。盡管有些瀏覽器會把段落結束標簽解釋為簡單地換行,但是這種行為在所有瀏覽器上并不都是一樣的。
pre 元素中允許的文本可以包括鏈接、圖像和水平分割線等。當把其他標簽(比如<a>標簽)放到pre塊中的時,就像放在 HTML/XHTML 文檔的其他部分中一樣。
在HTML4.01中,<pre>的width屬性已經廢棄,width屬性規定每行的最大字符數。
HTML5中請使用CSS代替。
code標簽(w3school)
定義計算機代碼文本。
在本例中的作用是能夠使過長的屬性值自動換行,不出現滾動條。
JSON.stringify(), JSON序列化
這個方法可以接收三個參數,后面兩個參數是可選的。
第二個參數是一個過濾函數或數組。
第三個參數 space
用來控制結果字符串里面的間距。如果是一個數字,則在字符串化時每一級別會比上一級別縮進多這個數字值的空格(最多10個空格);如果是一個字符串,則每一級別會比上一級別多縮進用該字符串(或該字符串的前十個字符)
JSON.stringify(value[, replacer [, space]])