就我目前4年(实习了1年,965了1年,996了2年,算3年感受少了,说是4年老司机也不为过吧。)的工做经验来看,JSON.stringify通常有如下用途:javascript
但其实除了上面两种经常使用的用法以外,JSON.stringify还有许多更增强大的特性,值得系统性学习。
关键是这些特性多是你开发过程当中常常用到的,只是你不知道而已。前端
也许你以为这是一篇枯燥的长篇大论的讲用法的博文,那么我就说几个有趣的场景吧:vue
若是这几个问题看了以后是一脸懵逼,那么必定要细细阅读一下这篇博文,答案就在文中。聪明的你必定会找到答案的。java
工做中经常使用JSON.stringify()ios
序列化:服务端存储重依赖前端的数据, localStorage/sessionStorage存储的数据(例如fabric.js的canvas模板数据,vue-amap的svg路径信息等等git
初识JSON.stringify()github
JSON.stringify(value, [ ,replacer[ ,space]]) 语法数据库
参数canvas
异常axios
JSON.stringify()描述
replacer 参数
space 参数
JSON.stringify()序列化循环引用时的问题
const obj = { foo: 'hi', bar: { name: 'bar', age: 3 }, baz: ['hello','javascript'] } const arr = ['hi', { name: 'bar', age: 3 }, ['hello','javascript']]; const deepCopy = JSON.parse(JSON.stringify(obj/arr))
深拷贝以后,deepCopy会生成一个内存独立的obj或者arr。
也就是说obj/arr与deepCopy存储在不一样的堆内存,修改obj/arr不会影响deepCopy,修改deepCopy也不会影响obj或者arr。
如果对于深浅拷贝不理解,建议先找资料系统性学习一下。
服务端存储重依赖前端的数据:例如fabric.js的canvas模板数据,vue-amap的svg路径信息等等。
localStorage/sessionStorage存储的数据: LocalStorage/SessionStorage The keys and the values are always strings。
例如Canvas,SVG信息,服务端作持久化。
const complexFabricJSCanvasTemplate = { ... }; const complexVueAMapSVGObject = { ... }; const JSONStr = JSON.stringify(complexFabricJSCanvasTemplate/complexVueAMapSVGObject); axios.post('/create', { name: 'fabric.js', // "vue-amap" data: JSONStr, }) .then((res)=>{ console.log(res); }) .catch((err)=>{ console.log(err); });
const testObj = {foo: 1, bar: 'hi', baz: { name: 'frankkai', age: 25 }} localStorage.setItem('testObj', JSON.stringify(testObj ));
若不转化,也不会报错,会致使存储失效:localStorage.getItem('testObj');// "[object Object]"
从服务端接口查询到存储好的Canvas或SVG数据,作解析后传入到fabric.js,vue-amap等进行绘制。
return new Promise((resolve)=>{ axios.get('/retrive', { name: 'fabric.js', // "vue-amap" }) .then((res)=>{ const complexFabricJSCanvasTemplate = JSON.parse(res.result); const complexVueAMapSVGObject = JSON.parse(res.result); resolve(complexFabricJSCanvasTemplate/complexVueAMapSVGObject); }) .catch((err)=>{ console.log(err); }); })
console.log(JSON.stringify({ x: 5, y: 6 })); // expected output: "{"x":5,"y":6}" console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)])); // expected output: "[3,"false",false]" console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] })); // expected output: "{"x":[10,null,null,null]}" console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))); // expected output: ""2006-01-02T15:04:05.000Z""
var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7}; // replacer为数组 JSON.stringify(foo, ['week', 'month']); // '{"week":45,"month":7}', 只返回week"和"month" // replacer为函数 function replacer(key, value) { if (typeof value === 'string') return undefined; return value; } JSON.stringify(foo, replacer); // '{"week":45,"month":7}',返回callback不为undefined的。
首行缩进两个空格。
JSON.stringify({ a: 2 }, null, ' '); // JSON.stringify({a:2}, null, 2)
=>
"{ "a": 2 }"
JSON.stringify(value, [ ,replacer[ ,space]]);
转化为JSON string的值。
过滤数据。
函数:replacer能够是函数,返回undefined时不输出数据,非undefined的数据被输出。
字符串数组:replacer能够是数组,通常是string,也能够是number。指定输出JSON的属性白名单。['week', 'month']
。
null或不写:replacer为null或者不写时,全部属性都被输出。null的话通常用于不过滤数据仅设置space的状况。
疑惑:replacer的数组中是数字?[1,2,3,4,5] ?
const arr = { 999: 'hi', foo: 'js', bar:' java' }; JSON.stringify(arr, [999, 'foo']); // 打印出"{"999":"hi","foo":"js"}"。 这里的999是number类型。
加强可读性的缩进空格或填充字符串。
JSON string。
序列化自引用的对象时会报这个错。高德地图的segments就是自引用对象。如何序列化自引用的对象可见下文。
包含突破Number存储上线的BitInt类型的obj,不能被序列化。
JSON.stringify({foo: 1n}) // TypeError “BigInt value can't be serialized in JSON”
若是想更好的使用JSON.stringify(),下面这些使用须知必定要掌握。
JSON.stringify({ foo: Symbol('foo') });// "{}"
JSON.stringify({ [Symbol('foo')]: 'foo' });// '{}' JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);// '{}'
var foo = [['foo',1]];var mp = new Map(foo);JSON.stringify(mp); // "{}"
let a = ['foo', 'bar']; a['baz'] = 'quux'; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ]; JSON.stringify(a); // '["foo","bar"]'
JSON.stringify([new Float32Array([1]), new Float64Array([1])]);// '[{"0":1},{"0":1}]'
究极使用示例:
JSON.stringify({}); // '{}' JSON.stringify(true); // 'true' JSON.stringify('foo'); // '"foo"' JSON.stringify([1, 'false', false]); // '[1,"false",false]' JSON.stringify([NaN, null, Infinity]); // '[null,null,null]' JSON.stringify({ x: 5 }); // '{"x":5}' JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) // '"2006-01-02T15:04:05.000Z"' JSON.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' JSON.stringify([new Number(3), new String('false'), new Boolean(false)]); // '[3,"false",false]' // String-keyed array elements are not enumerable and make no sense in JSON let a = ['foo', 'bar']; a['baz'] = 'quux'; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ] JSON.stringify(a); // '["foo","bar"]' JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }); // '{"x":[10,null,null,null]}' // Standard data structures JSON.stringify([new Set([1]), new Map([[1, 2]]), new WeakSet([{a: 1}]), new WeakMap([[{a: 1}, 2]])]); // '[{},{},{},{}]' // TypedArray JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]); // '[{"0":1},{"0":1},{"0":1}]' JSON.stringify([new Uint8Array([1]), new Uint8ClampedArray([1]), new Uint16Array([1]), new Uint32Array([1])]); // '[{"0":1},{"0":1},{"0":1},{"0":1}]' JSON.stringify([new Float32Array([1]), new Float64Array([1])]); // '[{"0":1},{"0":1}]' // toJSON() JSON.stringify({ x: 5, y: 6, toJSON(){ return this.x + this.y; } }); // '11' // Symbols: JSON.stringify({ x: undefined, y: Object, z: Symbol('') }); // '{}' JSON.stringify({ [Symbol('foo')]: 'foo' }); // '{}' JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]); // '{}' JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) { if (typeof k === 'symbol') { return 'a symbol'; } }); // undefined // Non-enumerable properties: JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) ); // '{"y":"y"}' // BigInt values throw JSON.stringify({x: 2n}); // TypeError: BigInt value can't be serialized in JSON
replacer能够是function,也能够是array。
function replacer(key="", value) { return value; }
做为function,有两个参数key 和 value。
默认状况下replacer函数的key为“”,对于对象中的每一个值,都会call一次这个函数。
`function replacer(key,value){ return value; } JSON.stringify({foo: false,bar:123},replacer);`
返回值有如下几种状况:
return 123; // "123"
return "foo"; // "foo"
return true; // "true"
return null; //"null"
return value;"{"foo":false,"bar":123}"
JSON.stringify({foo: false,bar:undefined},replacer);"{"foo":false}"。
使用强大的undefined是须要注意:
JSON.stringify()
的功劳。 v = JSON.stringify(v)
时,会将undefined类型的值自动过滤掉。
// axios源码 buildURL.js 37~56行: utils.forEach(params, function serialize(val, key) { if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); // 注意这里 } parts.push(encode(key) + '=' + encode(v)); }); });
function replacer(key,value){ if(typeof value ==='boolean'){return undefined} return value; } JSON.stringify([1, 'false', false],replacer); // "[1,"false",null]"
function replacer(key, value) { // 返回undefined过滤属性 if (typeof value === 'string') { return undefined; } return value; } var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7}; JSON.stringify(foo, replacer); // '{"week":45,"month":7}'
JSON.stringify(foo, ['week', 'month']); // '{"week":45,"month":7}',
JSON.stringify({ a: 2 }, null, ' '); // '{ // "a": 2 // JSON.stringify({ uno: 1, dos: 2 }, null, '\t'); // returns the string: // '{ // "uno": 1, // "dos": 2 // }'
若是要被字符串化的对象具备一个名为toJSON的属性,其值是一个函数,则该toJSON()方法将自定义JSON字符串化行为:代替被序列化的对象,该toJSON()方法返回的值将被序列化,而不是被序列化的对象。JSON.stringify()调用toJSON一个参数:
var obj = { data: 'data', toJSON (key) { return key; } }; JSON.stringify(obj); // '"""" JSON.stringify({ obj }) // '{"obj":"'obj'"}' JSON.stringify([ obj ]) // '["'0'"]'
TypeError: Converting circular structure to JSON
const circularReference = {}; circularReference.myself = circularReference; // Serializing circular references throws "TypeError: cyclic object value" JSON.stringify(circularReference);
路径规划plans的路径SVG信息segments对象。
需求是这样的,前端须要将路线的信息传递给后端,其中包括经纬度数组和SVG数组。
用JSON.stringify()序列化经纬度数组是ok的,可是序列化的SVG数组是自引用的,会报错。(是后来才知道这个SVG数组能够不往服务端存的,不过当时序列化报错是真的懵逼了)
使用Douglas Crockford的cycle.js
它在全局JSON对象上新增了2个方法:
myself:obj
替换为myself:{$ref: "$"}
)使用示例:
var circularReference = {}; circularReference.myself = circularReference; JSON.decycle(circularReference); // { "$ref": "$" }
不相等。
var a = JSON.stringify({ foo: "bar", baz: "quux" }) //'{"foo":"bar","baz":"quux"}' var b = JSON.stringify({ baz: "quux", foo: "bar" }) //'{"baz":"quux","foo":"bar"}' console.log(a === b) // false
localStorage只能存储string类型的数据,所以须要使用JSON.stringify()将对象序列化为JSON string。
var session = { 'screens': [], 'state': true }; session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 }); session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 }); session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 }); localStorage.setItem('session', JSON.stringify(session)); var restoredSession = JSON.parse(localStorage.getItem('session')); console.log(restoredSession);
值为undefined?
replacer对它作过滤了?
toJSON方法中作过滤了?
属性的enumerable值为false?
Symbol?
Map?Set?WeakMap?WeakSet?
找缘由吧。
v = JSON.stringify(v); // v = {foo: undefined} =>"{}"
const testObj = {foo: 1, bar: 'hi', baz: { name: 'frankkai', age: 25 }} JSON.stringify(testObj, null, 4);
=>
"{ "foo": 1, "bar": "hi", "baz": { "name": "frankkai", "age": 25 } }"
这是由于自引用以后,会限制死循环。
引擎应该是作了特殊的处理,发现这种无限循环时自动抛出异常。
这种对象不能序列化了吗?可使用cycle.js的decycle(序列化。
var circularReference = {}; circularReference.myself = circularReference; JSON.decycle(circularReference); // { "$ref": "$" }
参考资料:
期待和你们交流,共同进步,欢迎你们加入我建立的与前端开发密切相关的技术讨论小组:
- SegmentFault技术圈:ES新规范语法糖
- SegmentFault专栏:趁你还年轻,作个优秀的前端工程师
- 知乎专栏:趁你还年轻,作个优秀的前端工程师
- Github博客: 趁你还年轻233的我的博客
- 前端开发QQ群:660634678
- 微信公众号: 生活在浏览器里的咱们 / excellent_developers
努力成为优秀前端工程师!