qs

repository·main·Indexed 27 days ago

https://github.com/ljharb/qs

A querystring parser and stringifier for JavaScript that supports nesting and arrays with a depth limit. It provides robust capabilities for converting query strings into JavaScript objects via qs.parse() and converting objects back into query strings via qs.stringify(), featuring security-focused options for prototype handling, depth limits, and parameter limits.

Tokens
1.5K
Snippets
2
Records
11
Agent score
44%

What's inside qs

  1. Install and use the qs library

    main
    The qs library is a querystring parsing and stringifying utility designed with added security features. It is a successor to the original node-querystring module maintained by TJ Holowaychuk.
  2. Handle null values in qs

    main

    By default, null values are treated like empty strings (a=).

    • Distinguish null from empty strings: Use strictNullHandling: true in stringify to render null as a (no equals sign). In parse, this allows a to be parsed back as null.
    • Omit nulls: Use skipNulls: true in stringify to completely remove keys with null values from the output.
  3. Filter keys during stringification

    main

    Use the filter option in qs.stringify to include or exclude specific properties.

    • As a function: The function is called for each key. Returning undefined omits the property. You can use the prefix and value arguments to implement custom logic (e.g., prefix matching or type-based serialization).
    • As an array: Only the specified keys or array indices will be included.
    // Using a function to inject custom serialization
    qs.stringify(
        {
            range: new Range(30, 70),
        },
        {
            filter: (prefix, value) => {
                if (value instanceof Range) {
                    return `${value.from}...${value.to}`;
                }
                return value;
            },
        }
    );
    // 'range=30...70'
  4. Parse query strings with qs.parse()

    main

    Use qs.parse(string, [options]) to convert a query string into a JavaScript object. By default, qs supports nested objects using square bracket notation (e.g., foo[bar]=baz) and nested arrays (e.g., a[]=b&a[]=c).

    var qs = require('qs');
    var obj = qs.parse('a=c');
    // obj is { a: 'c' }
  5. Stringify objects with qs.stringify()

    main
    Use qs.stringify(object, [options]) to convert a JavaScript object into a query string. By default, it URI encodes the output and uses bracket notation for nested objects and arrays.
  6. Parse arrays with qs.parse()

    main

    Arrays can be parsed using [] notation or explicit indices.

    • Indices: a[0]=b&a[1]=c results in { a: ['b', 'c'] }.
    • Sparse Arrays: By default, qs compacts sparse arrays. Use allowSparse: true to preserve them.
    • Array Limits: By default, if an index is 20 or greater, the collection switches from an array to an object to prevent massive memory allocation. Use arrayLimit to change this threshold.
    • Mixed Notation: Mixing a[0]=b and a[key]=c results in an object { a: { '0': 'b', key: 'c' } }.
  7. Configure qs.stringify() options

    main

    The qs.stringify method accepts an options object:

    • encode: Set to false to disable URI encoding.
    • encodeValuesOnly: If true, only values are encoded, not keys.
    • encoder: A custom function for encoding. Can distinguish between type === 'key' and type === 'value'.
    • depth: Maximum nesting depth (default Infinity). Exceeding this throws a RangeError.
    • arrayFormat: Controls array serialization. Options: 'indices' (default), 'brackets', 'repeat', or 'comma'.
    • indices: Set to false to disable index-based array formatting.
    • allowDots: Enables dot notation for objects (e.g., a.b=c).
    • encodeDotInKeys: If true, encodes dots in keys (implies allowDots).
    • allowEmptyArrays: If true, allows foo[] in the output.
    • addQueryPrefix: If true, prepends ? to the string.
    • delimiter: Custom delimiter (e.g., ;).
    • serializeDate: Custom function to serialize Date objects.
    • sort: A function to sort parameter keys.
    • filter: A function or array to restrict which keys are included.
    • strictNullHandling: If true, null values are rendered without an = sign (e.g., a&b=).
    • skipNulls: If true, keys with null values are omitted entirely.
    • charset: Sets the character set.
    • charsetSentinel: Includes utf8=✓ to help detect charset.
    • format: Sets the space encoding format. Options: 'RFC3986' (default, uses %20) or 'RFC1738' (uses +).
  8. Configure qs.parse() options

    main

    The qs.parse method accepts an options object to control parsing behavior:

    • plainObjects: Returns objects created via { __proto__: null }. Prototype methods will not exist.
    • allowPrototypes: Allows user input to overwrite properties on the object prototype (use with caution).
    • depth: Sets the maximum nesting depth (default is 5).
    • strictDepth: If true, throws a RangeError when the depth limit is exceeded.
    • parameterLimit: Limits the number of &-delimited parameters (default is 1000).
    • throwOnLimitExceeded: If true, throws an error when parameterLimit or arrayLimit is exceeded.
    • ignoreQueryPrefix: If true, ignores a leading ? in the string.
    • delimiter: A string or RegExp to use as a delimiter instead of &.
    • allowDots: Enables dot notation for nesting (e.g., a.b=c).
    • decodeDotInKeys: Enables decoding dots in keys (implies allowDots).
    • allowEmptyArrays: Allows foo[] to result in an empty array [].
    • duplicates: Controls behavior for duplicate keys. Options: 'combine' (default, creates array), 'first', or 'last'.
    • charset: Sets the character set (e.g., 'iso-8859-1').
    • charsetSentinel: If true, uses the utf8 parameter to detect the correct charset.
    • interpretNumericEntities: Decodes &#...; numeric entities.
    • decoder: A custom function to override decoding of keys and values.
    • parseArrays: If false, prevents [] or [index] notation from being parsed as arrays.
  9. Parse a query string with parse()

    main
    Use the parse function to convert a query string into an object. This function handles various data types including objects, arrays, and primitive/scalar values (numbers, booleans, null, etc.) depending on the input string format.