標籤:json序列化 set pre 函數 ext rip str return lan
<!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序列化-化繁為簡