JSON
JSON简介
JSON---Javascript Object Notation,前两个单词大家应该都认识,最后一个notation,是“记号、标记法”的意思,连在一起,便成了JSON。它是一种轻量级的数据交换格式,是基于Javascript的一个子集,可以叫做Javascript对象表示法,是存储和交换文本信息的语法,但它并不是Javascript独有的数据格式,其它很多语言都可以对JSON进行解析和序列化。JSON的基本语法
① 并列的数据之间用逗号( , )分隔
② 映射用冒号( : )表示
③ 映射的集合用大括号( {} )表示
④ 并列数据的集合用方括号( [] )表示-
一个简单地例子
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> .wrap{ width: 400px; margin: 100px auto; border: 1px solid red; } .wrap::after{ display: block; content: ""; clear: both; } .top{ text-align: center; } .top p, .top h1{ margin: 0; } .box{ width: 195px; height: 210px; background: rgb(242,242,242); margin-bottom: 10px; float: left; color: red; text-align: center; } .box:nth-of-type(odd){ margin-right: 10px; } </style> </head> <body> <div class="wrap"> <div class="top"> <h1></h1> <p></p> </div> <div class="content"></div> </div> </body> <script type="text/javascript" src="jquery-3.2.1.min.js"></script> <script type="text/javascript"> var json = '{"title":"小老板大排档", "address":"古浪路703号","list":[{"name":"黄焖及米饭","price":"16","pl":["鸡","青椒","土豆"], "pic":"hmj.jpeg"}, {"name":"地锅鸡", "price":"28","pl":["鸡","面饼","麻椒"], "pic":"dgj.jpeg"}, {"name":"白斩鸡","price":"21","pl":["鸡","酱油","盐"], "pic":"bzj.jpeg"}, {"name":"叫花鸡", "price":"33","pl":["鸡","叫花"], "pic":"jhj.jpg"}]}' var obj=JSON.parse(json); console.log(obj) var h=document.getElementsByTagName("h1")[0]; var p=document.getElementsByTagName("p")[0]; var content=document.getElementsByClassName("content")[0]; h.innerHTML=obj.title; p.innerHTML="地址:"+obj.address; for(var i=0;i<obj.list.length;i++){ var divs=document.createElement("div"); divs.className="box"; content.appendChild(divs); divs.style.backgroundImage="url(img/"+obj.list[i].pic+")"; divs.style.backgroundRepeat="no-repeat"; divs.style.backgroundSize="contain"; divss=document.getElementsByClassName("box") var box1=document.createElement("div"); box1.style.marginTop="125px"; box1.innerHTML="菜名:"+obj.list[i].name+"<br/>"+"价格:"+obj.list[i].price+"<br/>"+"配料:"+obj.list[i].pl; divss[i].appendChild(box1) } </script></html>
运行结果如下: