- Json字符串转JavaScript对象
1 <html> 2 <body> 3 <h3>通过 JSON 字符串来创建对象</h3> 4 <p> 5 First Name: <span id="fname"></span><br /> 6 Last Name: <span id="lname"></span><br /> 7 </p> 8 <script type="text/javascript"> 9 var txt = '{"employees":[' + 10 '{"firstName":"Bill","lastName":"Gates" },' + 11 '{"firstName":"George","lastName":"Bush" },' + 12 '{"firstName":"Thomas","lastName":"Carter" }]}'; 13 14 obj = JSON.parse(txt); 15 16 document.getElementById("fname").innerHTML=obj.employees[1].firstName 17 document.getElementById("lname").innerHTML=obj.employees[1].lastName 18 </script> 19 </body> 20 </html>
注意:
eval() 函数使用的是 JavaScript 编译器,可解析 JSON 文本,然后生成 JavaScript 对象。必须把文本包围在括号中,这样才能避免语法错误:
var obj = eval ("(" + txt + ")");
- Json字符串转JavaScript对象2
1 <html> 2 <body> 3 <h3>通过 JSON 字符串来创建对象</h3> 4 <p> 5 First Name: <span id="fname"></span><br /> 6 Last Name: <span id="lname"></span><br /> 7 </p> 8 <script type="text/javascript"> 9 var txt = '{"employees":[' + 10 '{"firstName":"Bill","lastName":"Gates" },' + 11 '{"firstName":"George","lastName":"Bush" },' + 12 '{"firstName":"Thomas","lastName":"Carter" }]}'; 13 14 var obj = eval ("(" + txt + ")"); 15 16 document.getElementById("fname").innerHTML=obj.employees[1].firstName 17 document.getElementById("lname").innerHTML=obj.employees[1].lastName 18 </script> 19 </body> 20 </html>
- JavaScript对象转JSON字符串
1 </div> 2 <h3>JavaScript对象转换为Json字符串</h3> 3 <p> 4 all: <span id="all3"></span><br/> 5 </p> 6 <script type="text/javascript"> 7 var txt = '{"employees":[' + 8 '{"firstName":"Bill","lastName":"Gates" },' + 9 '{"firstName":"George2","lastName":"Bush2" },' + 10 '{"firstName":"Thomas","lastName":"Carter" }]}'; 11 12 var obj3 = eval("(" + txt + ")"); 13 document.getElementById("all3").innerHTML = JSON.stringify(obj3); 14 </script> 15 <div>