JSON.parse 反序列化
JSON.parse() 方法用来解析 JSON 字符串,构造由字符串描述的 JavaScript 值或对象。
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
JSON.stringify() 序列化
JSON.stringify() 方法将一个 JavaScript 对象或值转换为 JSON 字符串。
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify("foo"); // '"foo"'
JSON.stringify([1, "false", false]); // '[1,"false",false]'
JSON.stringify({ x: 5 }); // '{"x":5}'
const json = '{"result":true, "count":42}'; //json字符串,外面有单引号或者双引号包裹
const json = {"result":true, "count":42}; //json对象
const json = {result:true, count:42,name:"haha"}; //JavaScript对象
用法:
// 使用 JSON.stringify 转换为 JSON 字符串
// 然后使用 localStorage 保存在 session 名称里
localStorage.setItem('session', JSON.stringify(session));
// 然后是如何转换通过 JSON.stringify 生成的字符串,该字符串以 JSON 格式保存在 localStorage 里
var restoredSession = JSON.parse(localStorage.getItem('session'));
使用JQuery框架,前端传进的json数据必须是json字符串
使用axios框架来传递json,因为axios默认的content-type为application/json, 所以无需设置contentType。同时使用post方法,可以实现传递json对象,而无需在前端将json对象转成json字符串