标签:
JSON 语法是 JavaScript 对象表示法语法的子集。
JSON 值可以是:
说明:可简单的这样理解,放在{}里面的就是对象,放在[]里面的就是数组。关键是,可以无限的嵌套。
如:
以内部系统管理员为例:
{ "usertype": 2, "user_info":{ "userid":"xxxx", "name":"xxxx", "avatar":"xxxx" },//值为对象
"corp_info":{ "corpid":"wx6c698d13f7a409a4", }, "agent":[ {"agentid":0,"auth_type":1}, {"agentid":1,"auth_type":1}, {"agentid":2,"auth_type":1} ],//值为数组
"auth_info":{ "department":[ { "id":"2", "writable":"true" } ] }, "redirect_login_info":{ "login_ticket":"xxxx", "expires_in":36000 } }
JSON 数组在方括号中书写:
数组可包含多个对象:
{ "employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] }
在javascript中json格式的文本,可直接转换成javascript的对象:如下例子:
例子1:
<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);//var obj = eval ("(" + txt + ")");使用该语句也得可以
document.getElementById("fname").innerHTML=obj.employees[1].firstName
document.getElementById("lname").innerHTML=obj.employees[1].lastName
</script>
</body>
</html>
例2:
<script type="text/javascript">
var JSONObject= {
"name":"Bill Gates",
"street":"Fifth Avenue New York 666",
"age":56,
"phone":"555 1234567"};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById("jage").innerHTML=JSONObject.age
document.getElementById("jstreet").innerHTML=JSONObject.street
document.getElementById("jphone").innerHTML=JSONObject.phone
</script>
标签:
原文地址:http://www.cnblogs.com/shanwater/p/5616526.html