JSON.stringify 函数 (JavaScript)

将 JavaScript 值转换为 JavaScript 对象表示法 (Json) 字符串。

JSON.stringify(value [, replacer] [, space])

使用 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"]}'
*/

 

posted @ 2014-10-24 11:17  韩梦芫  阅读(358)  评论(0编辑  收藏  举报