本文基本使用谷歌翻譯加上自己的理解,權(quán)當(dāng)加深記憶。
npm
簡介
qs 是一個(gè)增加了一些安全性的查詢字符串解析和序列化字符串的庫。
主要維護(hù)者:Jordan Harband
最初創(chuàng)建者和維護(hù)者:TJ Holowaychuk
用法
var qs = require('qs');var assert = require('assert'); var obj = qs.parse('a=c');assert.deepEqual(obj, { a: 'c' }); var str = qs.stringify(obj);assert.equal(str, 'a=c');解析對象
qs.parse(string, [options]);
qs 允許在查詢字符串中使用[]的方式創(chuàng)建嵌套的對象。例如,字符串'foo[bar]=baz'可以轉(zhuǎn)換為:
assert.deepEqual(qs.parse('foo[bar]=baz'), { foo: { bar: 'baz' } });When using the plainObjects option the parsed value is returned as a null object, created via Object.create(null) and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like:
var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } });By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use plainObjects as mentioned above, or set allowPrototypes to true which will allow user input to overwrite those properties. WARNING It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option.
var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } });也可以解析 URI 編碼:
assert.deepEqual(qs.parse('a%5Bb%5D=c'), { a: { b: 'c' } });還可以像這樣嵌套對象:'foo[bar][baz]=foobarbaz':
assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { foo: { bar: { baz: 'foobarbaz' } } });當(dāng)使用嵌套對象時(shí),qs 在默認(rèn)情況下最多解析到的深度是第五層(注:從第一個(gè)方括號到算起,到第五個(gè)方括號),例如嘗試解析一個(gè)這樣的字符串'a[b][c][d][e][f][g][h][i]=j'將會得到以下結(jié)果:
var expected = { a: { b: { c: { d: { e: { f: { '[g][h][i]': 'j' } } } } } } }; var string = 'a[b][c][d][e][f][g][h][i]=j'; assert.deepEqual(qs.parse(string), expected);可以給 qs.parse 傳遞一個(gè) depth 參數(shù)覆蓋默認(rèn)值:
var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } });
新聞熱點(diǎn)
疑難解答
圖片精選