文件操作及json
- 文件写入 : file_put_contents()
- 读取文件: file_get_contents();
- 把数组转成json字符串 json_decode(数组);
- 把json字符串转成数组或者对象 json_encode(json字符串,true);
json数据格式 :主流的数据传输格式
主流的数据传输格式:1.json 2.xml;
json :字符串 ,在所有平台都有json格式 且格式是一样的 。是有严格格式的字符串。
let str = '{"name":"张三","age":20,"height":"178cm"}';
let str2 = '[{"name":"张三","age":20,"height":"178cm"},{"name":"李四","age":21,"height":"179cm"}]';
json的转换:
1.数组或者对象转成json字符串 JSON.stringify 2.json字符串转成对象或者数组
1.数组或者对象转成json字符串 JSON.stringify
let arr = [
{name:"zhangsan",age:20},
{name:"zhangsan2",age:21},
{name:"zhangsan3",age:22},
]
let josnstr = JSON.stringify(arr);
console.log(josnstr);
2.json字符串转成对象或者数组
let str = '{"name":"张三","age":20,"height":"178cm"}';
let str2 = '[{"name":"张三","age":20,"height":"178cm"},{"name":"李四","age":21,"height":"179cm"}]';
let arr = [
{name:"zhangsan",age:20},
{name:"zhangsan2",age:21},
{name:"zhangsan3",age:22},
]
var arr2 = JSON.parse(JSON.stringify(arr));
console.log(arr2);
json用处 1.数据交互 2.深拷贝;(注意 ,json会丢失属性 ,函数 ,undefined,map。。。)
let obj = {name:"1111",age:20,fn(){console.log(111)},c:undefined};
let obj2 = JSON.parse(JSON.stringify(obj));
obj2.age = 30;
console.log(obj2);
// console.log(obj);