• Use:
    • Parsing into objects
    • Parsing into arrays
    • The string is changed
    • Handling of null values
    • Under the dynamic hands

Use:

  • Download code: github.com/huangyangqu…
  • Run node index.js to view the output
var qs = require('qs');

var obj = qs.parse('a=c');
console.log('obj: ', obj);

var str = qs.stringify(obj);
console.log('str: ', str);
Copy the code

Parse into objects:

// Nested objects

var obj2 = qs.parse('foo[bar]=baz')
console.log('obj2: ', obj2);

var obj3 = qs.parse('foo[bar][baz]=foobarbaz')
console.log('obj3: ', obj3);
Copy the code

// Create an empty object

var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); console.log('nullObject: ', nullObject); Console. log('nullObject is empty ', nullobject.tostring)Copy the code

// Override the values on the prototype

var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true });
console.log('protoObject: ', protoObject);
Copy the code

// UrL-encoded string

const urlObj = qs.parse('a%5Bb%5D=c')
console.log('urlObj: ', urlObj);
Copy the code

// The nesting depth is 5 by default, which can be set to depth

var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });
console.log('deep: ', deep);
Copy the code

// The default number of parsing parameters is 1000. You can set this parameter using parameterLimit

var limited = qs.parse('a=b&c=d', { parameterLimit: 1 });
console.log('limited: ', limited);
Copy the code

// To bypass the leading question mark, use ignoreQueryPrefix:

var prefixed = qs.parse('? a=b&c=d', { ignoreQueryPrefix: true }); console.log('prefixed: ', prefixed);Copy the code

// There are specified delimiters, which can be set by delimiter:

var delimited = qs.parse('a=b; c=d', { delimiter: '; '}); console.log('delimited: ', delimited);Copy the code

// The delimiter can also be a regular expression:

var regexed = qs.parse('a=b; c=d,e=f', { delimiter: /[;,]/ }); console.log('regexed: ', regexed);Copy the code

// The allowDots option can be used to enable dot notation:

var withDots = qs.parse('a.b=c', { allowDots: true });
console.log('withDots: ', withDots);
Copy the code

// If you must work with older browsers or services, it is also supported to decode the percent-encoded octets to ISO-8859-1:

var oldCharset = qs.parse('a=%A7', { charset: 'iso-8859-1' });
console.log('oldCharset: ', oldCharset);
Copy the code

Parse to an array:

var withArray = qs.parse('a[]=b&a[]=c');
console.log('withArray: ', withArray);
Copy the code

// We can specify the position of the character in the array:

var withIndexes = qs.parse('a[1]=c&a[0]=b');
console.log('withIndexes: ', withIndexes);
Copy the code

Note that the only difference between an index in an array and a key in an object is that the value between the parentheses must be a number to create an array. When creating an array with a specific index, QS compresses the sparse array to preserve only the existing values of its order:

var noSparse = qs.parse('a[1]=b&a[15]=c');
console.log('noSparse: ', noSparse);
Copy the code

// You can also use the allowSparse option to parse sparse arrays:

var sparseArray = qs.parse('a[1]=2&a[6]=5', { allowSparse: true });
console.log('sparseArray: ', sparseArray);
Copy the code

// Note that the empty string is also a value and will be preserved:

var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c&a[3]=');
console.log('withIndexedEmptyString: ', withIndexedEmptyString);
Copy the code

Qs will also limit the maximum index specified in the array to 20. Any array member with an index greater than 20 is converted to an object with an index key. This is necessary to deal with cases where someone sends, for example, a[999999999] and takes a lot of time to iterate over this huge array.

var withMaxIndex = qs.parse('a[100]=b');
console.log('withMaxIndex: ', withMaxIndex);
Copy the code

// This limitation can be overridden by passing the arrayLimit option:

var withArrayLimit = qs.parse('a[101]=b', { arrayLimit: 101 });
console.log('withArrayLimit: ', withArrayLimit);

var withArrayLimit1 = qs.parse('a[102]=b', { arrayLimit: 101 });
console.log('withArrayLimit1: ', withArrayLimit1);
Copy the code

// To disable array parsing completely, set parseArrays to false:

var noParsingArrays = qs.parse('a[]=b&a[]=c', { parseArrays: false });
console.log('noParsingArrays: ', noParsingArrays);
var noParsingArrays = qs.parse('a[]=b&a[3]=c', { parseArrays: false }); 
console.log('noParsingArrays: ', noParsingArrays);
Copy the code

// If you mix symbols, QS will merge the two items into one object:

var mixedNotation = qs.parse('a[0]=b&a[b]=c');
console.log('mixedNotation: ', mixedNotation);
Copy the code

// You can also create arrays of objects:

var arraysOfObjects = qs.parse('a[][b]=c');
console.log('arraysOfObjects: ', arraysOfObjects);

var arraysOfObjects1 = qs.parse('a[b][]=c');
console.log('arraysOfObjects1: ', arraysOfObjects1);
Copy the code

// Use a comma to concatenate an array.

var arraysOfObjects = qs.parse('a=b,c', { comma: true })
console.log('arraysOfObjects: ', arraysOfObjects);
Copy the code

Note: (This does not convert nested objects, such as a={b:1},{c:d})

Stringing:

qs.stringify(object, [options]);

// When stringed, the qs URI encodes the output by default. The object is stringed as you would expect:

console.log(qs.stringify({ a: 'b' }));
console.log(qs.stringify({ a: { b: 'c' } }))
Copy the code

// This encoding can be disabled by setting the encode option to false:

var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false });
console.log('unencoded: ', unencoded);
Copy the code

// Key encoding can be disabled by setting the encodeValuesOnly option to true:

var encodedValues = qs.stringify(
    { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] },
    { encodeValuesOnly: true }
);
console.log('encodedValues: ', encodedValues);
Copy the code

// Encoding can also be set to a custom encoding method using the encoder option:

var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) {
    // Passed in values `a`, `b`, `c`
    console.log(str)
    return // Return encoded string
}})
console.log('encoded: ', encoded);
Copy the code

// (Note: if encode is false, the encoder option does not apply)

// Like an encoder, there is a decoder option for parsing to override the decoding of attributes and values:

var decoded = qs.parse('x=z', { decoder: function (str) {
    // Passed in values `x`, `z`
    return str + 'JOSHUA'// Return decoded string
}})
console.log(decoded);
Copy the code

// You can encode keys and values using different logic using the type parameter type provided to the encoder:

var encoded1 = qs.stringify({ a: { b: 'c' } }, { encoder: function (str, defaultEncoder, charset, type) {
    if (type === 'key') {
        return 'key' + str// Encoded key
    } else if (type === 'value') {
        return 'value' + str// Encoded value
    }
}})
console.log(encoded1);
Copy the code

// The type argument is also supplied to the decoder:

var decoded1 = qs.parse('x=z', { decoder: function (str, defaultDecoder, charset, type) {
    if (type === 'key') {
        return // Decoded key
    } else if (type === 'value') {
        return // Decoded value
    }
}})
console.log(decoded1);
Copy the code

// For clarity, the examples used in the tutorial may seem to go beyond this section, as if the output is not URI-encoded. // Note that during actual use, the return value in these cases will be URI-encoded.

// When arrays are stringed, by default they are given an explicit index:

console.log(qs.stringify({ a: ['b', 'c', 'd'] }));
// 'a[0]=b&a[1]=c&a[2]=d'
Copy the code

// You can override it by setting the index option to false:

console.log(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }));
// 'a=b&a=c&a=d'
Copy the code

// You can use the arrayFormat option to specify the format of the output array:

console.log(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }));
// 'a[0]=b&a[1]=c'
console.log(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }));
// 'a[]=b&a[]=c'
console.log(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }));
// 'a=b&a=c'
console.log(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' }));
// 'a=b,c'
Copy the code

// When objects are stringed, by default they are expressed in parentheses:

console.log(qs.stringify({ a: { b: { c: 'd', e: 'f' } } }));
// 'a[b][c]=d&a[b][e]=f'
Copy the code

// You can override it to use dot notation by setting the allowDots option to true:

console.log(qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }));
// 'a.b.c=d&a.b.e=f'
Copy the code

// Empty strings and empty values omit the value, but the equal sign (=) remains the same:

console.log(qs.stringify({ a: '' }));
Copy the code

// A key without a value (such as an empty object or array) returns nothing:

console.log('1', qs.stringify({ a: [] }));
console.log('2', qs.stringify({ a: {} }));
console.log('3', qs.stringify({ a: [{}] }));
console.log('4', qs.stringify({ a: { b: []} }));
console.log('5', qs.stringify({ a: { b: {}} }));
Copy the code

// Attributes set to undefined will be completely omitted:

console.log(qs.stringify({ a: null, b: undefined }));
Copy the code

// The query string can optionally be preceded by a question mark:

console.log(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }));
Copy the code

// Delimiters can also be overridden by stringify:

console.log(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }));
Copy the code

// If you only want to override the serialization of Date objects, you can provide a serializeDate option:

var date = new Date(7); console.log(qs.stringify({ a: date })); console.log(qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); }}));Copy the code

// You can use the sort option to influence the order of parameter keys:

function alphabeticalSort(a, b) {
    return a.localeCompare(b);
}
console.log(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }));
Copy the code

// Finally, you can use the filter option to restrict which keys can be included in the string-like output. // If you pass a function, call the function once for each key, get the return value by executing the function, replace the value of key. // Otherwise, if you pass an array, it will be used to select string-like attributes and array indexes:

function filterFunc(prefix, value) {
    if (prefix == 'b') {
        // Return an `undefined` value to omit a property.
        return;
    }
    if (prefix == 'e[f]') {
        return value.getTime();
    }
    if (prefix == 'e[g][0]') {
        return value * 2;
    }
    return value;
}
console.log('filter option')
console.log(qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }));
// 'a=b&c=d&e[f]=123&e[g][0]=4'
console.log(qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }));
// 'a=b&e=f'
console.log(qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }));
// 'a[0]=b&a[2]=d'
Copy the code

Null handling:

// By default, a null value is treated as an empty string:

var withNull = qs.stringify({ a: null, b: '' });
console.log('withNull: ', withNull);
Copy the code

// Parsing does not distinguish between arguments with and without an equal sign. Both are converted to empty strings.

var equalsInsensitive = qs.parse('a&b=');
console.log('equalsInsensitive: ', equalsInsensitive);
Copy the code

// To distinguish between null values and empty strings, use the strictNullHandling option. Null values have no = symbol in the result string:

var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true });
console.log('strictNull: ', strictNull);
Copy the code

// To resolve a value without = back to NULL, use the strictNullHandling option:

var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true });
console.log('parsedStrictNull: ', parsedStrictNull);
Copy the code

// To completely skip processing output for keys with null values, use the skipNulls option:

var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true });
console.log('nullsSkipped: ', nullsSkipped);
Copy the code

// If you are communicating with an older system, you can switch to ISO-8859-1 using the charset option:

Var iso = qs. Stringify ({æ : 'æ'}, {charset: 'iso - 8859-1}); console.log('iso: ', iso);Copy the code

// characters that do not exist in ISO-8859-1 will be converted to numeric entities, similar to what browsers do:

Var numeric = qs.stringify({a: '☺'}, {charset: 'ISL-8859-1'}); console.log('numeric: ', numeric);Copy the code

Under the dynamic hands

  • Follow me on GitHub @huangyangquang ⭐⭐
  • Welcome to follow my official account: Joshua, the front end upperclassman