qs
qs copied to clipboard
Feature request: option for deciding how to parse query without argument
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!
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?
"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!
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.
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.
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
.
Hi @ljharb I've pushed up a WIP patchset, ran into a small issue and was hoping to get your feedback. Thanks!