把 JSON 文本转换为 JavaScript 对象
JSON 最常见的用法之一,是从 web 服务器上读取 JSON 数据(作为文件或作为 HttpRequest),将 JSON 数据转换为 JavaScript 对象,然后在网页中使用该数据。
为了更简单地为您讲解,我们使用字符串作为输入进行演示(而不是文件)
json.html
<html>
<body>
<h2>
通过 JSON 字符串来创建对象
</h3>
<p>
First Name:
<span id="fname"></span>
<br />
Last Name:
<span id="lname"></span>
<br />
</p>
<script type="text/javascript">
var txt = '{"employees":[' + '{"firstName":"Bill","lastName":"Gates" },' + '{"firstName":"George","lastName":"Bush" },' + '{"firstName":"Thomas","lastName":"Carter" }]}';
var obj = eval("(" + txt + ")");
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>
</body>
</html>
<html>
<body>
<h2>
通过 JSON 字符串来创建对象
</h3>
<p>
First Name:
<span id="fname"></span>
<br />
Last Name:
<span id="lname"></span>
<br />
</p>
<script type="text/javascript">
var txt = '{"employees":[' + '{"firstName":"Bill","lastName":"Gates" },' + '{"firstName":"George","lastName":"Bush" },' + '{"firstName":"Thomas","lastName":"Carter" }]}'; var obj = eval("(" + txt + ")");
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>
</body>
</html>
或者:
obj = JSON.parse(txt);