URL Query string parser and stringifier. The package allows to customize parsing and stringifying process.
npm install @stein197/qs
Here is the example of simple usage:
import * as qs from "@stein197/qs";
qs.stringify({a: 1, b: 2}); // "a=1&b=2"
qs.parse("a=1&b=2"); // {a: 1, b: 2}
- Nesting structures support
- Omitting redundant indices
- Inferring arrays where possible
- Inferring primitive types where possible
- Inferring flags
- Encoding and decoding
- Sparse arrays support
- Custom encoders and decoders
You can pass to both functions complex structures, which includes objects and arrays:
qs.parse("a[b]=2"); // {a: {b: 2}}
qs.stringify({a: {b: 2}}); // "a[b]=2"
The complexity of structures is unlimited - you can parse/stringify structures of any depth and type (object or array)
The indices of arrays of stringified result could be omitted where possible. You can disable this option by providing indices
option with true
value. You cannot do this properly with qs, especially when it deals with deeply nested arrays.
qs.stringify({a: [1, 2, 3]}); // "a[]=1&a[]=2&a[]=3"
Indices could be ommited for more deep structures.
The arrays could be inferred from query string where possible:
qs.parse("a[]=1"); // {a: [1]}
qs.parse("a[0]=1"); // {a: [1]}
Arrays could be inferred from more deep structures.
By default, parse()
function will try to cast string values to corresponding types where possible (undefined, null, boolean or number).
qs.parse("a=undefined&b=null&c=false&d=-1"); // {a: undefined, b: null, c: false, d: -1}
When an item doesn't have both value and separator, then true
is returned for this specific key:
qs.parse("a=1&b"); // {a: 1, b: true}
qs.stringify({a: 1, b: true}); "a=1&b"
When parsing and stringifying, special characters will be percent-encoded/decoded:
qs.parse("a=%20"); // {a: " "}
qs.stringify({a: "&"}); // "a=%26"
Since the package supports arrays, it supports sparse ones:
qs.parse("a[1]=1"); // {a: [, 1]}
qs.stringify({a: [, 1]}); // "a[1]=1"
If it's not enough, then you can provide an encoder and a decoder down to both functions like as follows:
qs.parse("a.b=1&a.c=2", {
decode: (rawKey: string, rawValue: string, index: number) => {
return [
rawKey.toUpperCase().split("."),
rawValue * index
]
}
}); // {A: {B: 0, C: 2}}
qs.stringify({a: {b: 1, c: 2}}, {
encode: (keyPath: string[], value: any, index: number) => {
return [
keyPath.join(".").toUpperCase(),
String(value * index)
]
}
}); // "A.B=0&A.C=2"
To get more information on how this works, please refer to the documentation in the source code.
For more information, please refer to the documentation in source code.
browserify
. Createqs.min.js
file to include directly via<script />
tagsbuild
. Runclean
,test
,ts
andbrowserify
scriptsclean
. Remove compiled filestest
. Run unit teststs
. Compile the projectts:check
. Validate source code for compilation