1 | # querystring.js
|
2 |
|
3 | [![Build Status](https://travis-ci.org/john-yuan/querystring.js.svg?branch=master)](https://travis-ci.org/john-yuan/querystring.js)
|
4 |
|
5 | A query string encoder and decoder. It works like the `$.param(...)` function of jQuery and has the ability to decode the query string. Can be used in Node.js and browser side.
|
6 |
|
7 | Features:
|
8 |
|
9 | * Encode & Decode array (nested)
|
10 | * Encode & Decode object (nested)
|
11 |
|
12 | API:
|
13 |
|
14 | * [QS.encode(object, [keepArrayIndex])](#qsencodeobject-keeparrayindex)
|
15 | * [QS.decode(string)](#qsdecodestring)
|
16 |
|
17 | ## Install
|
18 |
|
19 | ```bash
|
20 | npm i x-query-string
|
21 | ```
|
22 |
|
23 | ## Example
|
24 |
|
25 | ```js
|
26 | var QS = require('x-query-string');
|
27 |
|
28 | // a=1&b=2
|
29 | QS.encode({ a: 1, b: 2 });
|
30 |
|
31 | // a%5B%5D=1&a%5B%5D=2&a%5B%5D=3 (a[]=1&a[]=2&a[]=3)
|
32 | QS.encode({ a: [1, 2, 3] });
|
33 |
|
34 | // a%5Bb%5D%5Bc%5D=3 (a[b][c]=3)
|
35 | QS.encode({ a: { b: { c: 3 } } });
|
36 | ```
|
37 |
|
38 | ## API
|
39 |
|
40 | ### QS.encode(object, [keepArrayIndex])
|
41 |
|
42 | * `object` {Object} The data to be encoded to query string
|
43 | * `boolean` {keepArrayIndex} Whether to always keep array index in the query string. If the array to be encoded just has one dimension, the index can be omitted. The default value is `false`.
|
44 | * Returns: {string} Returns the URI component encoded query string
|
45 |
|
46 | Encode the data to query string.
|
47 |
|
48 | ```js
|
49 | var QS = require('x-query-string');
|
50 |
|
51 | // a%5B%5D=1&a%5B%5D=2 (a[]=1&a[]=2)
|
52 | QS.encode({ a: [1, 2] });
|
53 |
|
54 | // a%5B0%5D=1&a%5B1%5D=2 (a[0]=1&a[1]=2)
|
55 | QS.encode({ a: [1, 2] }, true);
|
56 | ```
|
57 |
|
58 | ### QS.decode(string)
|
59 |
|
60 | * `string` {string} The query string to be decoded
|
61 | * Returns {Object} Returns the decoded data
|
62 |
|
63 | Decode the query string to a data object. The values in the result data object is `string` or `null`. This method will **NOT** try to parse `number` or `boolean` values.
|
64 |
|
65 | ```js
|
66 | var QS = require('x-query-string');
|
67 |
|
68 | QS.decode('a[]=1&a[]=2&b=false&c[d]=1&e=&f');
|
69 | // or (The query string below is url-encoded)
|
70 | QS.decode('a%5B%5D=1&a%5B%5D=2&b=false&c%5Bd%5D=1&e=&f');
|
71 | ```
|
72 |
|
73 | result:
|
74 |
|
75 | ```js
|
76 | {
|
77 | "a": [
|
78 | "1",
|
79 | "2"
|
80 | ],
|
81 | "b": "false",
|
82 | "c": {
|
83 | "d": "1"
|
84 | },
|
85 | "e": "",
|
86 | "f": null
|
87 | }
|
88 | ```
|
89 |
|
90 | ## License
|
91 |
|
92 | [MIT](./LICENSE "MIT")
|