目录
json数据在ajax实现异步交互时起到了很重要的作用,他可以返回请求的数据,然后利用客户端的js进行解析,这一点体现出js的强大
数字number 字符串string 布尔boolean
- [{
- "id" : 1 ,
- "name" : "xiaoming"
- },{
- "id" : 2 ,
- "name" : "xiaohong"
- }]
- //前后端分离,推荐后端返回给前端数据格式
- {
- "status" : 0 , //执行状态码
- "msg" : "SUCCESS", //说明文字信息,没有为NULL
- "data" :[{ //对象中嵌套数组,数组是返回的数据,
- "id" : 1 ,
- "name" : "xiaohong"
- },{
- "id" : 2,
- "name" : "xiaoming"
- }]
- }
Json中只要涉及到字符串就必须使用双引号,不支持undefined
- var jsonObj = '{ "name": "Lyt", "age": 18 }'
- var jsObj = JSON.parse(jsonObj)
- console.log(jsObj)
- var jsonObj = '{"name":"小明","age":18}'
- var jsObj = eval('('+jsonObj+')')
- console.log(jsObj)
- var jsonArray = '[{"name":"小明","age":18},{"name":"小红","age":19},{"name":"小蓝","age":20}]'
- var jsArray = eval('('+jsonArray+')')
- console.log(jsArray)
- var jsObj = {name:"Lyt",age:18}
- var jsonObj = JSON.stringify(jsObj)
- console.log(jsonObj)
通过for(let i in obj){}来获取,其中i为json对象obj的键名,获取该键对应的值,可以通过obj[i].xxx获取
- var clearRoom = {
- "2020-8-16": {
- name: "小明",
- age: 60,
- },
- "2020-8-17": {
- name: "小红",
- age: 50,
- },
- "2020-8-18": {
- name: "小李",
- age: 55,
- },
- "2020-8-19": {
- name: "小明",
- age: 65,
- },
- };
- let keyName = []; // 键名
- let keyValue = []; // 键值
- let keyWord = []; // 元素
- for (let date in clearRoom) {
- keyName.push(date);
- keyValue.push(clearRoom[date].name);
- keyWord.push(clearRoom[date].age);
- }
- console.log(keyName);
- console.log(keyValue);
- console.log(keyWord);
- let arr=[{name:"张三",age:22},{name:"张四",age:18},{name:"张五",age:28},{name:"李四",age:33},{name:"王五",age:55}]
- var obj={};
- arr.forEach(item=>{
- Object.keys(item).forEach(subItem=>{
- obj.hasOwnProperty(subItem) ? obj[subItem].push(item[subItem]) : obj[subItem] = [item[subItem]]
- })
- })
- console.log(obj)
- var clearRoom = {
- "2020-8-16": {
- name: "小明",
- age: 60,
- },
- "2020-8-17": {
- name: "小红",
- age: 50,
- },
- "2020-8-18": {
- name: "小李",
- age: 55,
- },
- "2020-8-19": {
- name: "小明",
- age: 65,
- },
- };
-
- var newArr = [];
- function change() {
- for (let date in clearRoom) {
- clearRoom[date].date = date;
- newArr.push(clearRoom[date]);
- }
- }
- change();
- console.log(newArr);