JSON用法
<!doctype html>
<html>
<head>
<title>JSON用法</title>
<meta charset="utf-8" />
<script>
window.onload=function(){
//定义一个JSON对象,用来存储用户信息,属性为string类型,值为任意类型
var person={"name":"张三","age":24,"height":180.5,"wife":null};
document.getElementById(‘info1‘).innerHTML="姓名:"+person.name+",年龄:"+person.age+",身高:"+person.height+",媳妇:"+person.wife;
//定义一个user对象
var user={
"name":{"first":"tom","last":"cruise"},
"age":25,
"address":{
"province":"江苏省",
"city":"南京市",
"district":"秦淮区",
"street":"龙蟠中路"},
"hobby":"吃饭"
};
document.getElementById("info2").innerHTML="姓:"+user.name.last+",名:"+user.name.first+",街道:"+user.address.street+",爱好:"+user.hobby;
//定义一个字符串数组
/*var names=new Array();
names[0]="tom";
names[1]="jack";
names[2]="alice";*/
//var names=new Array("tom","jack","alice");
var names=["tom","jack","alice"];
for(var i=0;i<names.length;i++){
//alert(names[i]);
}
//定义一个JSON对象数组,存储多个学生信息
var users=[{"name":"张敬浩","age":25,"sex":"女","address":"珠江路"},
{"name":"王照陆","age":22,"sex":"男","address":"龙蟠中路"},
{"name":"唐伯虎","age":26,"sex":"男","address":"山西路"}];
for(var i=0;i<users.length;i++){
document.getElementById("info3").innerHTML+=users[i].name+","+users[i].age+","+users[i].address+"<br/>"
}
//将JSON转换为字符串
var student={"name":"张三","age":24,"height":180.5,"wife":null};
var str=JSON.stringify(student);
//alert(str);
//将字符串转换为JSON
var str2=‘{"name":"tom","age":23}‘;
var json=JSON.parse(str2);
//alert(json.name);
//将字符串转换为JSON数组
var str3=‘[{"name":"张敬浩","age":25,"sex":"女","address":"珠江路"},{"name":"王照陆","age":22,"sex":"男","address":"龙蟠中路"},{"name":"唐伯虎","age":26,"sex":"男","address":"山西路"}]‘;
var json2=JSON.parse(str3);
alert(json2[1].name);
}
</script>
</head>
<body>
<div id="info1"></div>
<div id="info2"></div>
<div id="info3"></div>
</body>
</html>
时间: 2024-10-03 13:20:05