JavaScript對象與json之間的相互轉換

一、htmlhtml

<textarea id="ta1" rows="20" cols="50">

</textarea>
<textarea id="ta2" rows="20" cols="50">

</textarea>
<textarea id="ta3" rows="20" cols="50">

</textarea>
<textarea id="ta4" rows="20" cols="50">

</textarea>
<textarea id="ta5" rows="20" cols="50">

</textarea>
<textarea id="ta6" rows="20" cols="50">

</textarea>
<br>
<button onclick="printInfo()">轉數據</button>
<button onclick="printInfo2()">轉數據+過濾</button>
<div id="showInfo"></div>

二、JavaScriptapp

< script>
    var person = new Object();//{}
    person.name="jack";
    person.age=20;
    person.isSingleDog=true;
    person.say=function(){
        return "hello";
    }

    //轉成JSON
    var str1 = JSON.stringify(person);
    document.getElementById("ta1").value=str1;
    //格式化輸出JSON
    var str2 = JSON.stringify(person,null,4);
    document.getElementById("ta2").value=str2;
    //增長過濾
    var str3 = JSON.stringify(person,["name","age"],4);
    document.getElementById("ta3").value=str3;
    //增長過濾函數
    var str4 = JSON.stringify(person,function(key,value){
        switch(key){
            case "isSingleDog":
                if(value==true){
                    return false;
                }
                return value;
            case "age":
                return Number(value)+10;
            case "name":
                return undefined;
            default:
                return value;

        }
    },4);
    document.getElementById("ta4").value=str4;

    //JSON轉對象
    function printInfo(){
        var info = document.getElementById("ta5").value;
        var obj = JSON.parse(info);
        for(var i in obj){
            //print(i+":"+obj[i]);
            appendToShowInfo(i+":"+obj[i]);
        }
        if(obj instanceof Array){
            for(var i in obj){
                for(var j in obj[i]){
                    appendToShowInfo(j+":"+obj[i][j]);
                }
            }
        }

    }

    //JSON轉對象 + 過濾函數
        function printInfo2(){
        var info = document.getElementById("ta6").value;
        var obj = JSON.parse(info,function(key,value){
            switch(key){
                case "age":
                return Number(value)+10;
                default:
                return value;
            }
        });
        for(var i in obj){
            appendToShowInfo(i+":"+obj[i]);
        }    
    }
    function appendToShowInfo(msg){
        var showInfo = document.getElementById("showInfo");
        var p = document.createElement("p");
        p.innerHTML=msg;
        showInfo.appendChild(p);
    }

    function print(msg){
        document.write(msg);
        document.write("<br>");
    }


</script>
相關文章
相關標籤/搜索