JSON语法规则:
- 数据为 键 / 值 对;
- 数据由逗号分隔;
- 大括号保存对象;
- 方括号保存数组;
JSON数据:
"firstName":"John"
JSON对象:
{"firstName":"John", "lastName":"Doe"}
JSON数组:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
JSON字符串转换为JavaScript对象:
创建 JavaScript 字符串,字符串为 JSON 格式的数据:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
使用 JavaScript 内置函数 JSON.parse() 将字符串转换为 JavaScript 对象:
var obj = JSON.parse(text);
在页面中使用新的 JavaScript 对象:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>