Initial commit
[yaffs-website] / node_modules / qs / README.md
1 # qs
2
3 A querystring parsing and stringifying library with some added security.
4
5 [![Build Status](https://api.travis-ci.org/ljharb/qs.svg)](http://travis-ci.org/ljharb/qs)
6
7 Lead Maintainer: [Jordan Harband](https://github.com/ljharb)
8
9 The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring).
10
11 ## Usage
12
13 ```javascript
14 var qs = require('qs');
15 var assert = require('assert');
16
17 var obj = qs.parse('a=c');
18 assert.deepEqual(obj, { a: 'c' });
19
20 var str = qs.stringify(obj);
21 assert.equal(str, 'a=c');
22 ```
23
24 ### Parsing Objects
25
26 [](#preventEval)
27 ```javascript
28 qs.parse(string, [options]);
29 ```
30
31 **qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`.
32 For example, the string `'foo[bar]=baz'` converts to:
33
34 ```javascript
35 assert.deepEqual(qs.parse('foo[bar]=baz'), {
36   foo: {
37     bar: 'baz'
38   }
39 });
40 ```
41
42 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:
43
44 ```javascript
45 var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true });
46 assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } });
47 ```
48
49 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.
50
51 ```javascript
52 var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true });
53 assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } });
54 ```
55
56 URI encoded strings work too:
57
58 ```javascript
59 assert.deepEqual(qs.parse('a%5Bb%5D=c'), {
60   a: { b: 'c' }
61 });
62 ```
63
64 You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`:
65
66 ```javascript
67 assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), {
68   foo: {
69     bar: {
70       baz: 'foobarbaz'
71     }
72   }
73 });
74 ```
75
76 By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like
77 `'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be:
78
79 ```javascript
80 var expected = {
81   a: {
82     b: {
83       c: {
84         d: {
85           e: {
86             f: {
87               '[g][h][i]': 'j'
88             }
89           }
90         }
91       }
92     }
93   }
94 };
95 var string = 'a[b][c][d][e][f][g][h][i]=j';
96 assert.deepEqual(qs.parse(string), expected);
97 ```
98
99 This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`:
100
101 ```javascript
102 var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });
103 assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } });
104 ```
105
106 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.
107
108 For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option:
109
110 ```javascript
111 var limited = qs.parse('a=b&c=d', { parameterLimit: 1 });
112 assert.deepEqual(limited, { a: 'b' });
113 ```
114
115 An optional delimiter can also be passed:
116
117 ```javascript
118 var delimited = qs.parse('a=b;c=d', { delimiter: ';' });
119 assert.deepEqual(delimited, { a: 'b', c: 'd' });
120 ```
121
122 Delimiters can be a regular expression too:
123
124 ```javascript
125 var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ });
126 assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' });
127 ```
128
129 Option `allowDots` can be used to enable dot notation:
130
131 ```javascript
132 var withDots = qs.parse('a.b=c', { allowDots: true });
133 assert.deepEqual(withDots, { a: { b: 'c' } });
134 ```
135
136 ### Parsing Arrays
137
138 **qs** can also parse arrays using a similar `[]` notation:
139
140 ```javascript
141 var withArray = qs.parse('a[]=b&a[]=c');
142 assert.deepEqual(withArray, { a: ['b', 'c'] });
143 ```
144
145 You may specify an index as well:
146
147 ```javascript
148 var withIndexes = qs.parse('a[1]=c&a[0]=b');
149 assert.deepEqual(withIndexes, { a: ['b', 'c'] });
150 ```
151
152 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
153 to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving
154 their order:
155
156 ```javascript
157 var noSparse = qs.parse('a[1]=b&a[15]=c');
158 assert.deepEqual(noSparse, { a: ['b', 'c'] });
159 ```
160
161 Note that an empty string is also a value, and will be preserved:
162
163 ```javascript
164 var withEmptyString = qs.parse('a[]=&a[]=b');
165 assert.deepEqual(withEmptyString, { a: ['', 'b'] });
166
167 var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c');
168 assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] });
169 ```
170
171 **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
172 instead be converted to an object with the index as the key:
173
174 ```javascript
175 var withMaxIndex = qs.parse('a[100]=b');
176 assert.deepEqual(withMaxIndex, { a: { '100': 'b' } });
177 ```
178
179 This limit can be overridden by passing an `arrayLimit` option:
180
181 ```javascript
182 var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 });
183 assert.deepEqual(withArrayLimit, { a: { '1': 'b' } });
184 ```
185
186 To disable array parsing entirely, set `parseArrays` to `false`.
187
188 ```javascript
189 var noParsingArrays = qs.parse('a[]=b', { parseArrays: false });
190 assert.deepEqual(noParsingArrays, { a: { '0': 'b' } });
191 ```
192
193 If you mix notations, **qs** will merge the two items into an object:
194
195 ```javascript
196 var mixedNotation = qs.parse('a[0]=b&a[b]=c');
197 assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } });
198 ```
199
200 You can also create arrays of objects:
201
202 ```javascript
203 var arraysOfObjects = qs.parse('a[][b]=c');
204 assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] });
205 ```
206
207 ### Stringifying
208
209 [](#preventEval)
210 ```javascript
211 qs.stringify(object, [options]);
212 ```
213
214 When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect:
215
216 ```javascript
217 assert.equal(qs.stringify({ a: 'b' }), 'a=b');
218 assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
219 ```
220
221 This encoding can be disabled by setting the `encode` option to `false`:
222
223 ```javascript
224 var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false });
225 assert.equal(unencoded, 'a[b]=c');
226 ```
227
228 This encoding can also be replaced by a custom encoding method set as `encoder` option:
229
230 ```javascript
231 var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) {
232   // Passed in values `a`, `b`, `c`
233   return // Return encoded string
234 }})
235 ```
236
237 _(Note: the `encoder` option does not apply if `encode` is `false`)_
238
239 Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values:
240
241 ```javascript
242 var decoded = qs.parse('x=z', { decoder: function (str) {
243   // Passed in values `x`, `z`
244   return // Return decoded string
245 }})
246 ```
247
248 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.
249
250 When arrays are stringified, by default they are given explicit indices:
251
252 ```javascript
253 qs.stringify({ a: ['b', 'c', 'd'] });
254 // 'a[0]=b&a[1]=c&a[2]=d'
255 ```
256
257 You may override this by setting the `indices` option to `false`:
258
259 ```javascript
260 qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });
261 // 'a=b&a=c&a=d'
262 ```
263
264 You may use the `arrayFormat` option to specify the format of the output array:
265
266 ```javascript
267 qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })
268 // 'a[0]=b&a[1]=c'
269 qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })
270 // 'a[]=b&a[]=c'
271 qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })
272 // 'a=b&a=c'
273 ```
274
275 When objects are stringified, by default they use bracket notation:
276
277 ```javascript
278 qs.stringify({ a: { b: { c: 'd', e: 'f' } } });
279 // 'a[b][c]=d&a[b][e]=f'
280 ```
281
282 You may override this to use dot notation by setting the `allowDots` option to `true`:
283
284 ```javascript
285 qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true });
286 // 'a.b.c=d&a.b.e=f'
287 ```
288
289 Empty strings and null values will omit the value, but the equals sign (=) remains in place:
290
291 ```javascript
292 assert.equal(qs.stringify({ a: '' }), 'a=');
293 ```
294
295 Key with no values (such as an empty object or array) will return nothing:
296
297 ```javascript
298 assert.equal(qs.stringify({ a: [] }), '');
299 assert.equal(qs.stringify({ a: {} }), '');
300 assert.equal(qs.stringify({ a: [{}] }), '');
301 assert.equal(qs.stringify({ a: { b: []} }), '');
302 assert.equal(qs.stringify({ a: { b: {}} }), '');
303 ```
304
305 Properties that are set to `undefined` will be omitted entirely:
306
307 ```javascript
308 assert.equal(qs.stringify({ a: null, b: undefined }), 'a=');
309 ```
310
311 The delimiter may be overridden with stringify as well:
312
313 ```javascript
314 assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d');
315 ```
316
317 If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option:
318
319 ```javascript
320 var date = new Date(7);
321 assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A'));
322 assert.equal(
323     qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }),
324     'a=7'
325 );
326 ```
327
328 You may use the `sort` option to affect the order of parameter keys:
329
330 ```javascript
331 function alphabeticalSort(a, b) {
332   return a.localeCompare(b);
333 }
334 assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y');
335 ```
336
337 Finally, you can use the `filter` option to restrict which keys will be included in the stringified output.
338 If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you
339 pass an array, it will be used to select properties and array indices for stringification:
340
341 ```javascript
342 function filterFunc(prefix, value) {
343   if (prefix == 'b') {
344     // Return an `undefined` value to omit a property.
345     return;
346   }
347   if (prefix == 'e[f]') {
348     return value.getTime();
349   }
350   if (prefix == 'e[g][0]') {
351     return value * 2;
352   }
353   return value;
354 }
355 qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc });
356 // 'a=b&c=d&e[f]=123&e[g][0]=4'
357 qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] });
358 // 'a=b&e=f'
359 qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] });
360 // 'a[0]=b&a[2]=d'
361 ```
362
363 ### Handling of `null` values
364
365 By default, `null` values are treated like empty strings:
366
367 ```javascript
368 var withNull = qs.stringify({ a: null, b: '' });
369 assert.equal(withNull, 'a=&b=');
370 ```
371
372 Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings.
373
374 ```javascript
375 var equalsInsensitive = qs.parse('a&b=');
376 assert.deepEqual(equalsInsensitive, { a: '', b: '' });
377 ```
378
379 To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null`
380 values have no `=` sign:
381
382 ```javascript
383 var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true });
384 assert.equal(strictNull, 'a&b=');
385 ```
386
387 To parse values without `=` back to `null` use the `strictNullHandling` flag:
388
389 ```javascript
390 var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true });
391 assert.deepEqual(parsedStrictNull, { a: null, b: '' });
392 ```
393
394 To completely skip rendering keys with `null` values, use the `skipNulls` flag:
395
396 ```javascript
397 var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true });
398 assert.equal(nullsSkipped, 'a=b');
399 ```
400
401 ### Dealing with special character sets
402
403 By default the encoding and decoding of characters is done in `utf-8`. If you 
404 wish to encode querystrings to a different character set (i.e.
405 [Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the
406 [`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library:
407
408 ```javascript
409 var encoder = require('qs-iconv/encoder')('shift_jis');
410 var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder });
411 assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I');
412 ```
413
414 This also works for decoding of query strings:
415
416 ```javascript
417 var decoder = require('qs-iconv/decoder')('shift_jis');
418 var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder });
419 assert.deepEqual(obj, { a: 'こんにちは!' });
420 ```
421
422 ### RFC 3986 and RFC 1738 space encoding
423
424 RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible.
425 In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'.
426
427 ```
428 assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c');
429 assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c');
430 assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c');
431 ```