json是一种与语言无关的数据交换的格式,作用:
使用ajax进行前后台数据交换
移动端与服务端的数据交换
1.Json的格式与解析
json有两种格式:
1)对象格式:{"key1":obj,"key2":obj,"key3":obj...}
2)数组/集合格式:[obj,obj,obj...]
例如:user对象 用json数据格式表示
{"username":"zhangsan","age":28,"password":"123","addr":"北京"}
List<Product> 用json数据格式表示
[{"pid":"10","pname":"小米4C"},{},{}]
注意:对象格式和数组格式可以互相嵌套
注意:json的key是字符串 json的value是Object
json的解析:
json是js的原生内容,也就意味着js可以直接取出json对象中的数据
如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>insertBefore.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <ul> <li id="bj" name="beijing">北京</li> </ul> </body> <script language="JavaScript"> /** * 案例五 * { * "param1":"value1", * "param2":{}, * "param3":[{key:value,key:value},{key:value,key:value}] * } * * */ var json = { "key1":"value1", "key2":{"firstname":"张","lastname":"三丰","age":100}, "key3":[ {"name":"小双","age":28,"addr":"扬州"}, {"name":"建宁","age":18,"addr":"紫禁城"}, {"name":"阿珂","age":10,"addr":"山西"}, ] }; alert(json.key2.lastname); alert(json.key3[2].name); </script> </html>