query-string icon indicating copy to clipboard operation
query-string copied to clipboard

Parsing of `arrayFormat: 'comma'` not working for queries of single value with comma

Open marxlow opened this issue 5 years ago • 7 comments

Say we have an Object we are stringifying to become a query param of the following shape (notice the comma in the value)

  1. Create an object with its value as a single string / array of one string.
const singleQueryObject = { not_important: [ "I, am, one, single, value"]};

// OR (the value can also just be a plain string, not an array like the above)

const singleQueryObject = { not_important: "I, am, one, single, value" };
  1. We stringify it:
const stringifyResult = queryString.stringify(singleQueryObject, { arrayFormat: 'comma' });
//=>  'not_important=I%2C%20am%2C%20one%2C%20single%2C%20value'
  1. We parse it (Actual)
const parsedResult = queryString.parse(stringifyResult, { arrayFormat: 'comma' });
//=> { not_important: [ 'I', ' am', ' one', ' single', ' value' ] }

(Expected)

{ not_important: [ 'I, am, one, single, value' ] };

Work around (?)

This bug only occurs when there is a single value. So say if we run the same step as above with this object instead:

const singleQueryObject = { not_important: [ 'I, am, one, single, value', 'It works!'] };
const stringifyResult = queryString.stringify(singleQueryObject, { arrayFormat: 'comma' });
const parsedResult = queryString.parse(stringifyResult, { arrayFormat: 'comma' });

//=> { not_important: [ 'I, am, one, single, value', 'It works!' ] }

marxlow avatar Nov 17 '20 07:11 marxlow

@sindresorhus @Richienb This is also causing issues on our side ? Any timeline for this fix ?

Yashkochar20 avatar Nov 18 '20 18:11 Yashkochar20

// @mishugana

sindresorhus avatar Nov 18 '20 22:11 sindresorhus

@sindresorhus @mishugana any update on this ?

Yashkochar20 avatar Dec 07 '20 17:12 Yashkochar20

The current parse API doesn't appear to have enough information to solve this problem.

One solution might be an option to encode array-ness into the parameter key during stringify, resulting in something like myArray[]=a,b,c. I could imagine this gracefully degrading for backwards compatible if the development philosophy requires it.

cainlevy avatar Jan 12 '21 19:01 cainlevy

The workaround from #211 solved this problem for me.

nathan-logan avatar Sep 26 '22 03:09 nathan-logan

This line is causing the problem: https://github.com/sindresorhus/query-string/blob/main/index.js#L177

In order for this to be fixed in a backwards compatible fashion an option would need to be introduced that allows prevention of the use of 'encoded arrays'.

EECOLOR avatar Nov 01 '22 08:11 EECOLOR

qs library has the correct behavior for comma separated arrays

EECOLOR avatar Nov 01 '22 08:11 EECOLOR