把下面的JSON數(shù)據(jù)顯示在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."
}]
實(shí)現(xiàn)方式:
HTML:
<pre>
<code id="show"></code>
</pre>
JS:
var show = document.getElementById('show'),
newData = JSON.stringify(arr, null, 4);
show.innerHTML = newData;
結(jié)果圖:

說明:
pre標(biāo)簽(w3school)
pre元素可定義預(yù)格式化的文本。被包圍在pre元素中的文本通常會保留空格和換行符。而文本也會呈現(xiàn)為等寬字體。
pre標(biāo)簽一個常見的應(yīng)用就是用來表示計算機(jī)的源代碼。
可以導(dǎo)致段落斷開的標(biāo)簽(例如標(biāo)題、<p>、<address>標(biāo)簽)絕不能包含在pre定義的塊里。盡管有些瀏覽器會把段落結(jié)束標(biāo)簽解釋為簡單地?fù)Q行,但是這種行為在所有瀏覽器上并不都是一樣的。
pre 元素中允許的文本可以包括鏈接、圖像和水平分割線等。當(dāng)把其他標(biāo)簽(比如<a>標(biāo)簽)放到pre塊中的時,就像放在 HTML/XHTML 文檔的其他部分中一樣。
在HTML4.01中,<pre>的width屬性已經(jīng)廢棄,width屬性規(guī)定每行的最大字符數(shù)。
HTML5中請使用CSS代替。
code標(biāo)簽(w3school)
定義計算機(jī)代碼文本。
在本例中的作用是能夠使過長的屬性值自動換行,不出現(xiàn)滾動條。
JSON.stringify(), JSON序列化
這個方法可以接收三個參數(shù),后面兩個參數(shù)是可選的。
第二個參數(shù)是一個過濾函數(shù)或數(shù)組。
第三個參數(shù) space 用來控制結(jié)果字符串里面的間距。如果是一個數(shù)字,則在字符串化時每一級別會比上一級別縮進(jìn)多這個數(shù)字值的空格(最多10個空格);如果是一個字符串,則每一級別會比上一級別多縮進(jìn)用該字符串(或該字符串的前十個字符)
JSON.stringify(value[, replacer [, space]])