qs icon indicating copy to clipboard operation
qs copied to clipboard

Feature request: option for deciding how to parse query without argument

Open timhwang21 opened this issue 6 years ago • 6 comments

Hi,

I was wondering if it would be possible to support passing an option for deciding how to parse queries without arguments? Currently url?foo can be parsed as either the empty string or as null. I am wondering if it's possible to have the parser treat a query without arguments as true.

Some background: I ran into a case in our codebase which does this, it seemed odd to me but apparently there's nothing in the standards that forbid queries without arguments. Are there more specific standards (e.g. the node implementation) that this library is trying to adhere to?

Thanks!

timhwang21 avatar Aug 18 '17 15:08 timhwang21

I'm not sure what you mean by "without arguments" - in url?foo, foo is the query string; qs.parse('foo&bar=') indeed returns { bar: "", foo: "" }, and qs.stringify({ foo: '', bar: true })) returns 'foo=&bar=true'.

You can certainly do this, however:

qs.stringify({ foo: '', bar: null }, { strictNullHandling: true }); // 'foo&bar='
qs.parse('foo&bar=', { strictNullHandling: true }); // { bar: '', foo: null }

Does that cover your use case?

ljharb avatar Aug 22 '17 07:08 ljharb

"Query string field without a value" would probably be more accurate, sorry.

I was mainly wondering if something like this were possible -- basically, supporting valueless fields being parsed as having a given value:

qs.parse('foo&bar=', { parseEmptyValueAs: true }); // { bar: '', foo: true }
// possibly also useful
qs.parse('foo&bar=', { parseEmptyValueAs: '123' }); // { bar: '', foo: '123' }

Thanks!

timhwang21 avatar Aug 22 '17 11:08 timhwang21

That's interesting. Effectively, it'd be an option for both parse and stringify that defined what primitive "an absent value" was - so qs.stringify({ foo: 123, bar: 456 }, { emptyValue: 123 }) would give 'foo&bar=456'.

I think that's reasonable, since it's pretty cumbersome to do that otherwise.

ljharb avatar Aug 22 '17 16:08 ljharb

Sounds good, do you think it would make sense to (eventually) combine with strictNullHandling? Instead of true that option can just take whatever value you want the absent value to take. Otherwise the user may get unexpected results with { strictNullHandling: true, emptyValue: 123 } -- it'd be user error for sure, but can be reduced by consolidating the settings.

timhwang21 avatar Aug 22 '17 16:08 timhwang21

yeah, i'd think that the options would be incompatible - ie, strictNullHandling: true would throw when emptyValue is supplied, and emptyValue: null would be identical to strictNullHandling: true.

ljharb avatar Aug 23 '17 00:08 ljharb

Hi @ljharb I've pushed up a WIP patchset, ran into a small issue and was hoping to get your feedback. Thanks!

timhwang21 avatar Sep 16 '17 19:09 timhwang21