将JSON格式数据转换为javascript对象 JSON.parse()

<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" }]}';

obj = JSON.parse(txt);

document.getElementById("fname").innerHTML=obj.employees[1].firstName
document.getElementById("lname").innerHTML=obj.employees[1].lastName
</script>
</body>
</html>

对于较老的浏览器,可使用 JavaScript 库: https://github.com/douglascrockford/JSON-js

posted @ 2018-05-31 12:40  虚幻的街景  阅读(785)  评论(0编辑  收藏  举报