【javascript】javascript中的JSON.stringify函数的理解
将 JavaScript 值转换为 JavaScript 对象表示法 (Json) 字符串。
JSON.stringify(value [, replacer] [, space])
参数
返回值
一个包含 JSON 文本的字符串。
异常
异常 |
条件 |
---|---|
替换器参数无效 |
replacer 参数不是函数或数组。 |
值参数中不支持循环引用 |
value 参数包含循环引用。 |
如果 value 具有 toJSON 方法,则 JSON.stringify 函数使用该方法的返回值。 如果 toJSON 方法的返回值为 undefined,则不转换成员。 这使对象能够确定其自己的 JSON 表示形式。
将不会转换不具有 JSON 表示形式的值,例如 undefined。 在对象中,将丢弃这些值。 在数组中,会将这些值替换为 null。
字符串值以引号开始和结束。 所有 Unicode 字符可括在引号中,除了必须使用反斜杠进行转义的字符。 以下字符的前面必须是反斜杠:
-
引号 (")
-
反斜杠 ()
-
Backspace (b)
-
换页 (f)
-
换行符 (n)
-
回车 (r)
-
水平制表符 (t)
-
四个十六进制数字 (uhhhh)
执行顺序
在序列化过程中,如果 value 参数具有 toJSON 方法,则 JSON.stringify 会首先调用 toJSON 方法。 如果该方法不存在,则使用原始值。 紧接着,如果提供 replacer 参数,则该值(原始值或 toJSON 返回值)将替换为 replacer 参数的返回值。 最后,根据可选的 space 参数向该值添加空白以生成最终的 JSON 文本。
示例此示例使用 JSON.stringify 将contact对象转换为 JSON 文本。 定义memberfilter数组以便只转换surname和phone成员。 省略firstname成员。
var contact = new Object();
contact.firstname = "Jesper";
contact.surname = "Aaberg";
contact.phone = ["555-0100", "555-0120"];
var memberfilter = new Array();
memberfilter[0] = "surname";
memberfilter[1] = "phone";
var jsonText = JSON.stringify(contact, memberfilter, " ");
document.write(jsonText);
// Output:
// { "surname": "Aaberg", "phone": [ "555-0100", "555-0120" ] }
此示例使用带数组的 JSON.stringify。replaceToUpper函数将数组中的每个字符串转换为大写形式。
var continents = new Array();
continents[0] = "Europe";
continents[1] = "Asia";
continents[2] = "Australia";
continents[3] = "Antarctica";
continents[4] = "North America";
continents[5] = "South America";
continents[6] = "Africa";
var jsonText = JSON.stringify(continents, replaceToUpper);
function replaceToUpper(key, value) {
return value.toString().toUpperCase();
}
//Output:
// "EUROPE,ASIA,AUSTRALIA,ANTARCTICA,NORTH AMERICA,SOUTH AMERICA,AFRICA"
此示例使用 toJSON 方法将字符串值转换为大写形式。
var contact = new Object();
contact.firstname = "Jesper";
contact.surname = "Aaberg";
contact.phone = ["555-0100", "555-0120"];
contact.toJSON = function(key)
{
var replacement = new Object();
for (var val in this)
{
if (typeof (this[val]) === "string")
replacement[val] = this[val].toUpperCase();
else
replacement[val] = this[val]
}
return replacement;
};
var jsonText = JSON.stringify(contact);
document.write(jsonText);
// Output:
{"firstname":"JESPER","surname":"AABERG","phone":["555-0100","555-0120"]}
"{"firstname":"JESPER","surname":"AABERG","phone":["555-0100","555-0120"]}"
*/
要求
在以下文档模式中受到支持:Internet Explorer 8 标准、Internet Explorer 9 标准、Internet Explorer 10 标准、Internet Explorer 11 标准。Windows 应用商店 应用程序中也支持此项。请参阅 版本信息。
在以下文档模式中不受支持:Quirks、Internet Explorer 6 标准模式、Internet Explorer 7 标准模式。
请参见参考
JSON.parse 函数 (JavaScript) toJSON 方法 (Date) (JavaScript)- 上一篇: 【php】数组
- 下一篇: 【json】json_encode() 函数介绍