JavaScript JSON.stringify()
JSON.stringify() 方法用於將JavaScript 值轉換為JSON 字符串。
語法
JSON.stringify(value[, replacer[, space]])
參數說明:
- value:
必需, 一個有效的JSON 字符串。
- replacer:
可選。 用於轉換結果的函數或數組。
如果replacer 為函數,則JSON.stringify 將調用該函數,並傳入每個成員的鍵和值。 使用返回值而不是原始值。 如果此函數返回undefined,則排除成員。 根對象的鍵是一個空字符串:""。
如果replacer 是一個數組,則僅轉換該數組中具有鍵值的成員。 成員的轉換順序與鍵在數組中的順序一樣。 當value 參數也為數組時,將忽略replacer 數組。
- space:
可選,文本添加縮進、空格和換行符,如果space 是一個數字,則返回值文本在每個級別縮進指定數目的空格,如果space 大於10,則文本縮進10 個空格。 space 有可以使用非數字,如:\t。
返回值:
返回包含JSON 文本的字符串。
實例
實例
var str = {"name":"本教程", "site":"http://www.w3big.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 用於格式化輸出
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 用於格式化輸出
嘗試一下»