JavaScript--字符串与JSON对象相互转换

JSON.parse()

兼容性:Chrome,Firefox (Gecko) 3.5 (1.9.1),IE 8.0,Safari 4.0

JSON.parse('[1, 5, "false"]');

JSON.parse('{"p": 5}', function (k, v) {
    if(k === '') return v;     // 如果到了最顶层,则直接返回属性值,
    return v * 2;              // 否则将属性值变为原来的 2 倍。
});                            // { p: 10 }

JSON.stringify()
兼容性:Chrome,Firefox (Gecko) 3.5 (1.9.1),IE 8.0,Safari 4.0
    var student = new Object();
    student.name = "Lanny";
    student.age = "25";
    student.location = "China";
    var json1 = JSON.stringify(student);
    //{"name":"Lanny","age":"25","location":"China"}
    
    //只保留:name及locaiton
    var json2 = JSON.stringify(student,["name","location"]);
    //{"name":"Lanny","location":"China"}

    //处理特定属性
    var json3 = JSON.stringify(student, function (key, value) {
        switch (key){
            case "name":
                return "my name is " + value;
            default :
                return value;
        }
    });
    //{"name":"my name is Lanny","age":"25","location":"China"}

posted @ 2015-11-29 15:23  常平  阅读(158)  评论(0编辑  收藏  举报