首页 > 代码库 > JSON序列化-化繁为简

JSON序列化-化繁为简

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JOSN对象</title>
    <script>
        var book={
            title:"php 最佳实践",
            authors:[jack],
            edition:3,
            year:2017
        };


        //JSON.stringify()有三个参数分别是json对象,过滤器(可以是数组or函数),是否在josn字符串中保留缩进(这个参数意义不大可忽略)
        var jsonText=JSON.stringify(book);
        var jsonText1=JSON.stringify(book,["title","year"]);
        var jsonText2=JSON.stringify(book,function (key,value) {
            switch (key){
                case "title":
                    return "java 从入门到精通";
                case "year":
                    return 2018;
                case "edition":
                    return undefined;
                default:
                    return value;
            }
        });


        console.log(jsonText);//{"title":"php 最佳实践","authors":["jack"],"edition":3,"year":2017}
        console.log(jsonText1);//{"title":"php 最佳实践","year":2017}
        console.log(jsonText2);//{"title":"java 从入门到精通","authors":["jack"],"year":2018}


        //JSON.parse(arg1,arg2) 可以接受2个参数一个是json字符串,一个是过滤函数
        var jsonObject=JSON.parse(jsonText);
        var jsonObject1=JSON.parse(jsonText,function(key,value){
            if(key==="year"){
                return 2019
            }else if(key==="title"){
                return "javascript 从入门到精通";
            }else{
                return value;
            }
        });


        console.log(jsonObject);//Object {title: "php 最佳实践", authors: Array(1), edition: 3, year: 2017}
        console.log(jsonObject1);//Object {title: "javascript 从入门到精通", authors: Array(1), edition: 3, year: 2019}
        
    </script>
</head>
<body>

</body>
</html>

 

JSON序列化-化繁为简