原文:https://technet.microsoft.com/zh-cn/sysinternals/cc836459
url JSON.stringify 函数
将 JavaScript 值转换为 JavaScript 对象表示法 (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, "\t");
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"]}'
*/