b494369afb6165cffe115d8fa7171164df1d267221c15684e1ff41f011f670bd84855005afe1d14650301af3be3b7a469590b7dc63c71738327b48dab0144e 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. # qs <sup>[![Version Badge][2]][1]</sup>
  2. [![github actions][actions-image]][actions-url]
  3. [![coverage][codecov-image]][codecov-url]
  4. [![dependency status][deps-svg]][deps-url]
  5. [![dev dependency status][dev-deps-svg]][dev-deps-url]
  6. [![License][license-image]][license-url]
  7. [![Downloads][downloads-image]][downloads-url]
  8. [![npm badge][npm-badge-png]][package-url]
  9. A querystring parsing and stringifying library with some added security.
  10. Lead Maintainer: [Jordan Harband](https://github.com/ljharb)
  11. The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring).
  12. ## Usage
  13. ```javascript
  14. var qs = require('qs');
  15. var assert = require('assert');
  16. var obj = qs.parse('a=c');
  17. assert.deepEqual(obj, { a: 'c' });
  18. var str = qs.stringify(obj);
  19. assert.equal(str, 'a=c');
  20. ```
  21. ### Parsing Objects
  22. [](#preventEval)
  23. ```javascript
  24. qs.parse(string, [options]);
  25. ```
  26. **qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`.
  27. For example, the string `'foo[bar]=baz'` converts to:
  28. ```javascript
  29. assert.deepEqual(qs.parse('foo[bar]=baz'), {
  30. foo: {
  31. bar: 'baz'
  32. }
  33. });
  34. ```
  35. 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:
  36. ```javascript
  37. var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true });
  38. assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } });
  39. ```
  40. 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.
  41. ```javascript
  42. var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true });
  43. assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } });
  44. ```
  45. URI encoded strings work too:
  46. ```javascript
  47. assert.deepEqual(qs.parse('a%5Bb%5D=c'), {
  48. a: { b: 'c' }
  49. });
  50. ```
  51. You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`:
  52. ```javascript
  53. assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), {
  54. foo: {
  55. bar: {
  56. baz: 'foobarbaz'
  57. }
  58. }
  59. });
  60. ```
  61. By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like
  62. `'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be:
  63. ```javascript
  64. var expected = {
  65. a: {
  66. b: {
  67. c: {
  68. d: {
  69. e: {
  70. f: {
  71. '[g][h][i]': 'j'
  72. }
  73. }
  74. }
  75. }
  76. }
  77. }
  78. };
  79. var string = 'a[b][c][d][e][f][g][h][i]=j';
  80. assert.deepEqual(qs.parse(string), expected);
  81. ```
  82. This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`:
  83. ```javascript
  84. var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });
  85. assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } });
  86. ```
  87. The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number.
  88. For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option:
  89. ```javascript
  90. var limited = qs.parse('a=b&c=d', { parameterLimit: 1 });
  91. assert.deepEqual(limited, { a: 'b' });
  92. ```
  93. To bypass the leading question mark, use `ignoreQueryPrefix`:
  94. ```javascript
  95. var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true });
  96. assert.deepEqual(prefixed, { a: 'b', c: 'd' });
  97. ```
  98. An optional delimiter can also be passed:
  99. ```javascript
  100. var delimited = qs.parse('a=b;c=d', { delimiter: ';' });
  101. assert.deepEqual(delimited, { a: 'b', c: 'd' });
  102. ```
  103. Delimiters can be a regular expression too:
  104. ```javascript
  105. var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ });
  106. assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' });
  107. ```
  108. Option `allowDots` can be used to enable dot notation:
  109. ```javascript
  110. var withDots = qs.parse('a.b=c', { allowDots: true });
  111. assert.deepEqual(withDots, { a: { b: 'c' } });
  112. ```
  113. ### Parsing Arrays
  114. **qs** can also parse arrays using a similar `[]` notation:
  115. ```javascript
  116. var withArray = qs.parse('a[]=b&a[]=c');
  117. assert.deepEqual(withArray, { a: ['b', 'c'] });
  118. ```
  119. You may specify an index as well:
  120. ```javascript
  121. var withIndexes = qs.parse('a[1]=c&a[0]=b');
  122. assert.deepEqual(withIndexes, { a: ['b', 'c'] });
  123. ```
  124. Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number
  125. to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving
  126. their order:
  127. ```javascript
  128. var noSparse = qs.parse('a[1]=b&a[15]=c');
  129. assert.deepEqual(noSparse, { a: ['b', 'c'] });
  130. ```
  131. Note that an empty string is also a value, and will be preserved:
  132. ```javascript
  133. var withEmptyString = qs.parse('a[]=&a[]=b');
  134. assert.deepEqual(withEmptyString, { a: ['', 'b'] });
  135. var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c');
  136. assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] });
  137. ```
  138. **qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will
  139. instead be converted to an object with the index as the key. This is needed to handle cases when someone sent, for example, `a[999999999]` and it will take significant time to iterate over this huge array.
  140. ```javascript
  141. var withMaxIndex = qs.parse('a[100]=b');
  142. assert.deepEqual(withMaxIndex, { a: { '100': 'b' } });
  143. ```
  144. This limit can be overridden by passing an `arrayLimit` option:
  145. ```javascript
  146. var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 });
  147. assert.deepEqual(withArrayLimit, { a: { '1': 'b' } });
  148. ```
  149. To disable array parsing entirely, set `parseArrays` to `false`.
  150. ```javascript
  151. var noParsingArrays = qs.parse('a[]=b', { parseArrays: false });
  152. assert.deepEqual(noParsingArrays, { a: { '0': 'b' } });
  153. ```
  154. If you mix notations, **qs** will merge the two items into an object:
  155. ```javascript
  156. var mixedNotation = qs.parse('a[0]=b&a[b]=c');
  157. assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } });
  158. ```
  159. You can also create arrays of objects:
  160. ```javascript
  161. var arraysOfObjects = qs.parse('a[][b]=c');
  162. assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] });
  163. ```
  164. ### Stringifying
  165. [](#preventEval)
  166. ```javascript
  167. qs.stringify(object, [options]);
  168. ```
  169. When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect:
  170. ```javascript
  171. assert.equal(qs.stringify({ a: 'b' }), 'a=b');
  172. assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
  173. ```
  174. This encoding can be disabled by setting the `encode` option to `false`:
  175. ```javascript
  176. var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false });
  177. assert.equal(unencoded, 'a[b]=c');
  178. ```
  179. Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`:
  180. ```javascript
  181. var encodedValues = qs.stringify(
  182. { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] },
  183. { encodeValuesOnly: true }
  184. );
  185. assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h');
  186. ```
  187. This encoding can also be replaced by a custom encoding method set as `encoder` option:
  188. ```javascript
  189. var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) {
  190. // Passed in values `a`, `b`, `c`
  191. return // Return encoded string
  192. }})
  193. ```
  194. _(Note: the `encoder` option does not apply if `encode` is `false`)_
  195. Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values:
  196. ```javascript
  197. var decoded = qs.parse('x=z', { decoder: function (str) {
  198. // Passed in values `x`, `z`
  199. return // Return decoded string
  200. }})
  201. ```
  202. You can encode keys and values using different logic by using the type argument provided to the encoder:
  203. ```javascript
  204. var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str, defaultEncoder, charset, type) {
  205. if (type === 'key') {
  206. return // Encoded key
  207. } else if (type === 'value') {
  208. return // Encoded value
  209. }
  210. }})
  211. ```
  212. The type argument is also provided to the decoder:
  213. ```javascript
  214. var decoded = qs.parse('x=z', { decoder: function (str, defaultDecoder, charset, type) {
  215. if (type === 'key') {
  216. return // Decoded key
  217. } else if (type === 'value') {
  218. return // Decoded value
  219. }
  220. }})
  221. ```
  222. Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage.
  223. When arrays are stringified, by default they are given explicit indices:
  224. ```javascript
  225. qs.stringify({ a: ['b', 'c', 'd'] });
  226. // 'a[0]=b&a[1]=c&a[2]=d'
  227. ```
  228. You may override this by setting the `indices` option to `false`:
  229. ```javascript
  230. qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });
  231. // 'a=b&a=c&a=d'
  232. ```
  233. You may use the `arrayFormat` option to specify the format of the output array:
  234. ```javascript
  235. qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })
  236. // 'a[0]=b&a[1]=c'
  237. qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })
  238. // 'a[]=b&a[]=c'
  239. qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })
  240. // 'a=b&a=c'
  241. ```
  242. When objects are stringified, by default they use bracket notation:
  243. ```javascript
  244. qs.stringify({ a: { b: { c: 'd', e: 'f' } } });
  245. // 'a[b][c]=d&a[b][e]=f'
  246. ```
  247. You may override this to use dot notation by setting the `allowDots` option to `true`:
  248. ```javascript
  249. qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true });
  250. // 'a.b.c=d&a.b.e=f'
  251. ```
  252. Empty strings and null values will omit the value, but the equals sign (=) remains in place:
  253. ```javascript
  254. assert.equal(qs.stringify({ a: '' }), 'a=');
  255. ```
  256. Key with no values (such as an empty object or array) will return nothing:
  257. ```javascript
  258. assert.equal(qs.stringify({ a: [] }), '');
  259. assert.equal(qs.stringify({ a: {} }), '');
  260. assert.equal(qs.stringify({ a: [{}] }), '');
  261. assert.equal(qs.stringify({ a: { b: []} }), '');
  262. assert.equal(qs.stringify({ a: { b: {}} }), '');
  263. ```
  264. Properties that are set to `undefined` will be omitted entirely:
  265. ```javascript
  266. assert.equal(qs.stringify({ a: null, b: undefined }), 'a=');
  267. ```
  268. The query string may optionally be prepended with a question mark:
  269. ```javascript
  270. assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d');
  271. ```
  272. The delimiter may be overridden with stringify as well:
  273. ```javascript
  274. assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d');
  275. ```
  276. If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option:
  277. ```javascript
  278. var date = new Date(7);
  279. assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A'));
  280. assert.equal(
  281. qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }),
  282. 'a=7'
  283. );
  284. ```
  285. You may use the `sort` option to affect the order of parameter keys:
  286. ```javascript
  287. function alphabeticalSort(a, b) {
  288. return a.localeCompare(b);
  289. }
  290. assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y');
  291. ```
  292. Finally, you can use the `filter` option to restrict which keys will be included in the stringified output.
  293. If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you
  294. pass an array, it will be used to select properties and array indices for stringification:
  295. ```javascript
  296. function filterFunc(prefix, value) {
  297. if (prefix == 'b') {
  298. // Return an `undefined` value to omit a property.
  299. return;
  300. }
  301. if (prefix == 'e[f]') {
  302. return value.getTime();
  303. }
  304. if (prefix == 'e[g][0]') {
  305. return value * 2;
  306. }
  307. return value;
  308. }
  309. qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc });
  310. // 'a=b&c=d&e[f]=123&e[g][0]=4'
  311. qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] });
  312. // 'a=b&e=f'
  313. qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] });
  314. // 'a[0]=b&a[2]=d'
  315. ```
  316. ### Handling of `null` values
  317. By default, `null` values are treated like empty strings:
  318. ```javascript
  319. var withNull = qs.stringify({ a: null, b: '' });
  320. assert.equal(withNull, 'a=&b=');
  321. ```
  322. Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings.
  323. ```javascript
  324. var equalsInsensitive = qs.parse('a&b=');
  325. assert.deepEqual(equalsInsensitive, { a: '', b: '' });
  326. ```
  327. To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null`
  328. values have no `=` sign:
  329. ```javascript
  330. var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true });
  331. assert.equal(strictNull, 'a&b=');
  332. ```
  333. To parse values without `=` back to `null` use the `strictNullHandling` flag:
  334. ```javascript
  335. var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true });
  336. assert.deepEqual(parsedStrictNull, { a: null, b: '' });
  337. ```
  338. To completely skip rendering keys with `null` values, use the `skipNulls` flag:
  339. ```javascript
  340. var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true });
  341. assert.equal(nullsSkipped, 'a=b');
  342. ```
  343. ### Dealing with special character sets
  344. By default the encoding and decoding of characters is done in `utf-8`. If you
  345. wish to encode querystrings to a different character set (i.e.
  346. [Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the
  347. [`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library:
  348. ```javascript
  349. var encoder = require('qs-iconv/encoder')('shift_jis');
  350. var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder });
  351. assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I');
  352. ```
  353. This also works for decoding of query strings:
  354. ```javascript
  355. var decoder = require('qs-iconv/decoder')('shift_jis');
  356. var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder });
  357. assert.deepEqual(obj, { a: 'こんにちは!' });
  358. ```
  359. ### RFC 3986 and RFC 1738 space encoding
  360. RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible.
  361. In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'.
  362. ```
  363. assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c');
  364. assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c');
  365. assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c');
  366. ```
  367. ## Security
  368. Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report.
  369. ## qs for enterprise
  370. Available as part of the Tidelift Subscription
  371. The maintainers of qs and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-qs?utm_source=npm-qs&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
  372. [package-url]: https://npmjs.org/package/qs
  373. [npm-version-svg]: https://versionbadg.es/ljharb/qs.svg
  374. [deps-svg]: https://david-dm.org/ljharb/qs.svg
  375. [deps-url]: https://david-dm.org/ljharb/qs
  376. [dev-deps-svg]: https://david-dm.org/ljharb/qs/dev-status.svg
  377. [dev-deps-url]: https://david-dm.org/ljharb/qs#info=devDependencies
  378. [npm-badge-png]: https://nodei.co/npm/qs.png?downloads=true&stars=true
  379. [license-image]: https://img.shields.io/npm/l/qs.svg
  380. [license-url]: LICENSE
  381. [downloads-image]: https://img.shields.io/npm/dm/qs.svg
  382. [downloads-url]: https://npm-stat.com/charts.html?package=qs
  383. [codecov-image]: https://codecov.io/gh/ljharb/qs/branch/main/graphs/badge.svg
  384. [codecov-url]: https://app.codecov.io/gh/ljharb/qs/
  385. [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/qs
  386. [actions-url]: https://github.com/ljharb/qs/actions