首页 > 编程语言 > 详细

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

时间:2015-11-29 16:21:17      阅读:268      评论:0      收藏:0      [点我收藏+]

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"}

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

原文:http://www.cnblogs.com/c2603/p/4848164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!