json学习小记
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 </head> 7 <body> 8 <p> 9 name:<span id="name"></span><br /> 10 address:<span id="address"></span><br /> 11 age:<span id="age"></span><br /> 12 phone:<span id="phone"></span> 13 </p> 14 <p> 15 json数组1: 16 <span id="arrJson1"></span><br /> 17 json数组2: 18 <span id="arrJson2"></span> 19 </p> 20 <p> 21 First Name: <span id="fname"></span><br /> 22 Last Name: <span id="lname"></span><br /> 23 </p> 24 </body> 25 <script type="text/javascript"> 26 //普通json对象定义 27 var stus={ 28 "name":"bill", 29 "address":"Shenzhen", 30 "age":25, 31 "phone":110 32 }; 33 document.getElementById("name").innerText=stus.name; 34 document.getElementById("address").innerHTML=stus.address; 35 document.getElementById("age").innerText=stus.age; 36 document.getElementById("phone").innerText=stus.phone; 37 38 //json数组 39 var arrJson = { 40 "employees": [{ 41 "firstName": "John", 42 "lastName": "Doe" 43 }, { 44 "firstName": "Anna", 45 "lastName": "Smith" 46 }, { 47 "firstName": "Peter", 48 "lastName": "Jones" 49 }] 50 } 51 document.getElementById("arrJson1").innerText=arrJson.employees[0].firstName +" "+ arrJson.employees[0].lastName; 52 document.getElementById("arrJson2").innerText=arrJson.employees[1].firstName +" "+ arrJson.employees[1].lastName; 53 54 //创建json语法的js字符串 55 var txt = '{ "employees" : [' + 56 '{ "firstName":"Bill" , "lastName":"Gates" },' + 57 '{ "firstName":"George" , "lastName":"Bush" },' + 58 '{ "firstName":"Thomas" , "lastName":"Carter" } ]}'; 59 //eval() 函数使用的是 JavaScript 编译器,可解析 JSON 文本,然后生成 JavaScript 对象。必须把文本包围在括号中,这样才能避免语法错误: 60 var obj=eval("("+txt+")"); 61 obj.employees[0].firstName=obj.employees[1].firstName; 62 obj.employees[0].lastName=obj.employees[1].lastName; 63 document.getElementById("fname").innerHTML=obj.employees[0].firstName; 64 document.getElementById("lname").innerHTML = obj.employees[0].lastName; 65 66 </script> 67 </html>