25.javascript json
1.JSON格式大致是如下样子
大括号包裹数据,数据已键值对形式存在,键需要用引号,接着使用冒号:,再接着就是其值。
多个键值对用逗号隔开。
{ "employees":[ {"firstName":"Bill", "lastName":"Gates"}, {"firstName":"Steve", "lastName":"Jobs"}, {"firstName":"Alan", "lastName":"Turing"} ] }
{"firstName":"Bill", "lastName":"Gates"}
2.字符串格式的JSON数据转换成JSON请使用JSON.parse(text);
var text = '{ "employees" : [' + '{ "firstName":"Bill" , "lastName":"Gates" },' + '{ "firstName":"Steve" , "lastName":"Jobs" },' + '{ "firstName":"Alan" , "lastName":"Turing" } ]}'; var obj = JSON.parse(text);
3.调用json数据:
<p id="demo"></p> <script> document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName; </script>
4.将JSON数据转换成字符串JSON.stringify(obj);
var obj = {"name":"Bill", "age":62, "city":"Seatle"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON;