http://msdn.microsoft.com/zh-cn/library/ie/cc836459.aspx
此示例使用 JSON.stringify 序列化为 JSON 文本的 contact 对象。memberfilter 数组中定义,以便序列化仅 surname 和 phone 成员。firstname 成员省略。
JavaScript
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"); /* The value of jsonText is: '{ "surname": "Aaberg", "phone": [ "555-0100", "555-0120" ] }' */
此示例使用 JSON.stringify 序列化数组。replaceToUpper 函数在数组中的每个字符串转换为大写。
JavaScript
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); /* The value of jsonText is: '"EUROPE,ASIA,AUSTRALIA,ANTARCTICA,NORTH AMERICA,SOUTH AMERICA,AFRICA"' */ function replaceToUpper(key, value) { return value.toString().toUpperCase(); }
此示例使用 toJSON 方法序列化字符串成员值为大写。
JavaScript
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); /* The value of jsonText is: '{"firstname":"JESPER","surname":"AABERG","phone":["555-0100","555-0120"]}'
本文通过三个示例介绍了如何使用 JSON.stringify 方法来序列化 JavaScript 对象。包括选择性地序列化对象属性、将数组元素转换为大写及将字符串成员值转换为大写。
824

被折叠的 条评论
为什么被折叠?



