面试官:qs 的stringify第二个参数都支持哪些属性?
假如您只是用简单的用stringify和parse ,不妨看看下面的内容!
qs官网
基本操作
{ encode: false }
默认是编码的
qs.stringify({"a b":'出门带口罩'});///"a%20b=%E5%87%BA%E9%97%A8%E5%B8%A6%E5%8F%A3%E7%BD%A9"不编码时:
qs.stringify({"a b":'出门带口罩'},{encode:false});///"a b=出门带口罩"只编码值:
qs.stringify({"a b":'出门带口罩'},{encodeValuesOnly:true});// "a b=%E5%87%BA%E9%97%A8%E5%B8%A6%E5%8F%A3%E7%BD%A9"对undefined的解决
默认会忽略值为undefined的key
qs.stringify({a:undefined});// ""可以通过filter自己设置行为
qs.stringify( { a: undefined }, { filter: (key, value) => { return value === undefined ? "undefined" : value; }, }, );// "a=undefined"对null的解决
默认行为
编码
qs.stringify({ a: null, b: '' });// "a=&b="解码
qs.parse("a=&b=");// {a: "", b: ""}区分 null 与 ''
编码
qs.stringify({ a: null, b: '' }, { strictNullHandling: true })"a&b="解码
qs.parse('a&b=', { strictNullHandling: true })// {a: null, b: ""}跳过null
qs.stringify({ a: 'b', c: null}, { skipNulls: true })// "a=b"空对象和空数组会忽略
qs.stringify({ a: [] }); qs.stringify({ a: {} }); qs.stringify({ a: [{}] }); qs.stringify({ a: { b: [] } }); qs.stringify({ a: { b: {} } });// ""用filter过滤
是函数时,返回undefined 会被忽略
qs.stringify( { a: 1, b: 2 }, { filter: (key, value) => { if (key === "a") { return; } return value; }, }, );// b=2是数组时,保留指定的key
qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] });"a=b&e=f"对数组的解决
默认行为
qs.stringify({ a: ['b', 'c', 'd'] },{encodeValuesOnly:true});// 'a[0]=b&a[1]=c&a[2]=d'生成表单提交时的样子
qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });"a=b&a=c&a=d"qs.stringify({ a: ['b', 'c','d'] }, { arrayFormat: 'repeat' })"a=b&a=c&a=d"对?的解决
stringify 生成?号
qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true })// "?a=b&c=d"parse 忽略?号
qs.parse("?a=b&c=d",{ ignoreQueryPrefix: true })//{a: "b", c: "d"}对原生属性的解决
默认会被忽略
qs.parse('a[hasOwnProperty]=b')//{}不继承原型链
qs.parse('a[hasOwnProperty]=b', { plainObjects: true })
image.png
覆盖原生属性
qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true })
image.png
encoder 与 decoder
自己设置编码
qs.stringify( { a: { b: "c" } }, { encoder: function(str, defaultEncoder, charset, type) { if (type === "key") { return; // Encoded key } else if (type === "value") { return; // Encoded value } }, }, );自己设置解码
qs.parse("x=z", { decoder: function(str, defaultEncoder, charset, type) { if (type === "key") { return; // Decoded key } else if (type === "value") { return; // Decoded value } }, });基本规则
对嵌套层数的限制
默认5层
qs.parse('a[b][c][d][e][f][g][h][i]=j')
image.png
对参数个数的限制
默认1000 个
qs.parse('a=b&c=d', { parameterLimit: 1 });// {a: "b"}结语
qs 对数组和对象提供很多形式的解决方式,例如
qs.parse('a.b=c', { allowDots: true });// { a: { b: 'c' } }qs.parse('a[1]=b', { arrayLimit: 0 })//a: {1: "b"}在字符集上的设定
qs.stringify({ ?: '?' }, { charset: 'iso-8859-1' })不逐个列举,如有需要,建议仔细看一下官网,省时省力!