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