JSON是前後兩端傳輸數據的一種比較輕量的格式
JSON分為兩種結構:對象、數組
{'key1':value1,'key2':value2,'key3':value3}
[a,b,c]
var jsonText='{"employees":[{"name":"小A","birth":"2021-09-24"},\
{"name":"小B","birth":"2021-08-24"}]}'
var jsonObj = JSON.parse(jsonText,(key,value)=>{
if(key=="birth"){
return new Date(value);
}
else{
return value
}
})
console.log(jsonObj.employees)
console.log(jsonObj.employees[1].birth)
下面使用一下之前講過的 arrow function,讓程式更簡潔
var jsonObj = JSON.parse(jsonText,(key,value)=>{if(key=="birth")return new Date(value);else return value})
""
括起來\
else return value
,沒寫會出錯der<p id="demo" style="font-size: 30px;">demo</p>
<script>
//整個object框起來當作字串
var jsonText='{"employees":[{"name":"小A","age":20},{"name":"小B","age":21},{"name":"小C","age":22}],\
"boss":[{"name":"大A","age":30},{"name":"大B","age":31}]}';
//反斜線是為了換行
jobj=JSON.parse(jsonText);
console.log(jobj);
console.log(jobj.employees);
console.log(jobj.boss);
for(let i=0;i<jobj.boss.length;i++){
console.log(jobj.boss[i].name);
}
var demo =document.getElementById("demo");
var frag=0;
demo.onmouseover =()=>{
demo.style.color="";
if(frag==0){
demo.innerHTML=jobj.boss[0].name;
frag=1;
}else if(frag==1){
demo.innerHTML = jobj.boss[1].name;
frag=0;
}
}
demo.onmouseleave =()=>{
demo.innerHTML="不告訴你 boss是誰"
demo.style.color="pink";
}
</script>