zoukankan      html  css  js  c++  java
  • JSON序列化选项

    JSON.stringify()除了接受序列化js对象外,还可以接受另外的两个参数,这两个参数用于指定使用什么样的方式序列化js对象。

    第一个参数是个过滤器,可以一个数组或者一个函数;第二个参数是一个选项,表示是否在JSON字符串中保留缩进。

    实例1:对象序列化,使用数组作为过滤器

     var book = {
                title:"JavaScript Learn",
                author:["wang","jie"],
                edition:3,
                year:2015
            }
            var jsonText = JSON.stringify(book,["title","year"]);   //对象序列化,使用数组作为过滤器
    
            alert(jsonText);

    实例2:对象序列化,使用函数作为过滤器

      var book = {
                title:"JavaScript Learn",
                author:["wang","jie"],
                edition:3,
                year:2015
            }
            var jsonText = JSON.stringify(book,function(key,value){
                switch (key){
                    case "author":
                        return value.join(",");
                    case "year":
                        return 10000;
                    case "edition":
                        return undefined;
                    default :
                        return value;
                }
            });   //对象序列化,使用函数作为过滤器
    
            alert(jsonText);

    JSON.stringify()方法的第三个参数用于控制结果的缩进和空白符。
    实例3:在每个级别缩进四个空白符。

    var book = {
                title:"JavaScript Learn",
                author:["wang","jie"],
                edition:3,
                year:2015
            }
    
            var jsonText  = JSON.stringify(book,null,4)
    
            alert(jsonText);

    实例4:插入" - -"

     var book = {
                title:"JavaScript Learn",
                author:["wang","jie"],
                edition:3,
                year:2015
            }
    
            var jsonText  = JSON.stringify(book,null," - -")
    
            alert(jsonText);
  • 相关阅读:
    codeforces 269B Greenhouse Effect
    codeforces 5C Longest Regular Bracket Sequence
    codeforces 225C Barcode
    codeforces 279C Ladder
    CodeForces 479E Riding in a Lift
    CodeForces 351A Jeff and Rounding
    POJ-1579-201308122106.txt
    表达式求值-201308081712.txt
    Encoding-201308072147.txt
    A + B Problem II201308072001.txt
  • 原文地址:https://www.cnblogs.com/scnuwangjie/p/4921778.html
Copyright © 2011-2022 走看看