UNPKG

2.44 kBMarkdownView Raw
1# querystring.js
2
3[![npm version](https://img.shields.io/npm/v/x-query-string.svg)](https://www.npmjs.com/package/x-query-string)
4[![Build Status](https://travis-ci.org/john-yuan/querystring.js.svg?branch=master)](https://travis-ci.org/john-yuan/querystring.js)
5[![install size](https://packagephobia.now.sh/badge?p=x-query-string)](https://packagephobia.now.sh/result?p=x-query-string)
6[![npm downloads](https://img.shields.io/npm/dm/x-query-string.svg)](http://npm-stat.com/charts.html?package=x-query-string)
7
8A 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.
9
10Features:
11
12* Encode & Decode array (nested)
13* Encode & Decode object (nested)
14
15API:
16
17* [QS.encode(object, [keepArrayIndex])](#qsencodeobject-keeparrayindex)
18* [QS.decode(string)](#qsdecodestring)
19
20## Install
21
22```bash
23npm i x-query-string
24```
25
26## Example
27
28```js
29var QS = require('x-query-string');
30
31// a=1&b=2
32QS.encode({ a: 1, b: 2 });
33
34// a%5B%5D=1&a%5B%5D=2&a%5B%5D=3 (a[]=1&a[]=2&a[]=3)
35QS.encode({ a: [1, 2, 3] });
36
37// a%5Bb%5D%5Bc%5D=3 (a[b][c]=3)
38QS.encode({ a: { b: { c: 3 } } });
39```
40
41## API
42
43### QS.encode(object, [keepArrayIndex])
44
45* `object` {Object} The data to be encoded to query string
46* `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`.
47* Returns: {string} Returns the URI component encoded query string
48
49Encode the data to query string.
50
51```js
52var QS = require('x-query-string');
53
54// a%5B%5D=1&a%5B%5D=2 (a[]=1&a[]=2)
55QS.encode({ a: [1, 2] });
56
57// a%5B0%5D=1&a%5B1%5D=2 (a[0]=1&a[1]=2)
58QS.encode({ a: [1, 2] }, true);
59```
60
61### QS.decode(string)
62
63* `string` {string} The query string to be decoded
64* Returns {Object} Returns the decoded data
65
66Decode 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.
67
68```js
69var QS = require('x-query-string');
70
71QS.decode('a[]=1&a[]=2&b=false&c[d]=1&e=&f');
72// or (The query string below is url-encoded)
73QS.decode('a%5B%5D=1&a%5B%5D=2&b=false&c%5Bd%5D=1&e=&f');
74```
75
76result:
77
78```js
79{
80 "a": [
81 "1",
82 "2"
83 ],
84 "b": "false",
85 "c": {
86 "d": "1"
87 },
88 "e": "",
89 "f": null
90}
91```
92
93## License
94
95[MIT](./LICENSE "MIT")