ljharb / qs

A querystring parser with nesting support
BSD 3-Clause "New" or "Revised" License
8.47k stars 731 forks source link

`arrayFormat: 'comma'` Does Not Wrap Single Item as Array When Parsing #505

Closed jon9090 closed 3 months ago

jon9090 commented 3 months ago

Description: When using the arrayFormat: 'comma' option with qs.stringify, an array with a single item is not wrapped as an array when parsed with qs.parse. This behavior leads to inconsistencies, especially when expecting the parsed result to always be an array regardless of the number of items.

stackblitz example

Example:

const qs = require('qs');

const arrayWithOneItem = ['apple'];
const options = { arrayFormat: 'comma' };

const queryString = qs.stringify({ fruits: arrayWithOneItem }, options);
console.log(queryString); // Output: "fruits=apple"

const parsed = qs.parse(queryString, options);
console.log(parsed); // Output: { fruits: 'apple' } // Expected: { fruits: ['apple'] }

Expected Behavior: When parsing a query string generated with arrayFormat: 'comma', a single item should be wrapped as an array. The expected output should be:

{ fruits: ['apple'] }

Actual Behavior: The single item is not wrapped as an array:

{ fruits: 'apple' }

Environment:

Steps to Reproduce:

  1. Create an array with a single item.
  2. Use qs.stringify with arrayFormat: 'comma'.
  3. Parse the resulting query string with qs.parse using the same arrayFormat.

Additional Context: This behavior causes issues when the consistency of data types is important, particularly when handling query strings with arrays that might have a variable number of items.

ljharb commented 3 months ago

That’s what the commaRoundTrip option is for in stringify.