ljharb / qs

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

qs.parse omitting empty string keys #432

Open Coobaha opened 2 years ago

Coobaha commented 2 years ago

Hi, it will be nice to have this part configurable:

https://github.com/ljharb/qs/blob/542a5c7ff88d7229efa2e22c7c8a7d69375f5e72/lib/parse.js#L150-L152

current output:

qs.parse("=1&=2") === {}
qs.parse(" =1& =2") === { " ": ["1","2"] }

expected output :

qs.parse("=1&=2", { allowEmptyKeys: true }) === { "": ["1","2"] }

If you are ok - I can open a PR

ljharb commented 2 years ago

Please link me if I'm wrong, but I don't believe the spec permits empty keys in a query string. What's your use case/software where that's expected?

Coobaha commented 2 years ago

Thanks for the fast reply, I was using this as a reference:

new URLSearchParams('=1').getAll('') // ['1']

Our use case is that we need to evaluate user input in HTTP client editor, in some cases key might be not present yet or really evaluates to empty string. As a workaround I am assigning empty key names to temporal key and after parsing replacing them back :D This also requires preserving initial keys order, so hack becomes quite complex..

I can also imagine that some server/api might use this empty param name, even if it is not part of any RFC

ljharb commented 2 years ago

"USP supports it" is a good argument, although your use cases are not convincing - if the key's not present yet, then the value isn't either, and I'm not clear on why the key would really evaluate to an empty string.

The PR adding this would have to add it to both parse and stringify, so that there could be a round trip.

Additionally, what happens with =1&=2, in the arrayFormat repeat vs brackets? What about []=1&[]=2?

Coobaha commented 2 years ago

Great! i will open a pr then soon and we can continue there 🙏

ljharb commented 2 years ago

To be clear: a PR will need:

Coobaha commented 2 years ago

@ljharb opened #433 👍