ljharb / qs

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

[New] `parse`/`stringify`: add `allowEmptyArrays` option to allow [] in object values #487

Closed aks- closed 6 months ago

aks- commented 6 months ago

This PR adds allowEmptyArrays option which let's you keep empty arrays in the object values and address this issue

Without allowEmptyArrays option

qs.stringify({ foo: [], bar: baz }) // 'bar=baz'
qs.parse(qs.stringify({ foo: [], bar: baz })) // { bar: baz }

With allowEmptyArrays options set to true

qs.stringify({ foo: [], bar: baz }, { allowEmptyArrays: true }) // 'foo[]&bar=baz'
qs.parse(qs.stringify({ foo: [], bar: baz })) // { foo: [], bar: baz }
aks- commented 6 months ago

@ljharb qs.stringify({ foo: [], bar: 'baz' }, { allowEmptyArrays: true }) produces foo[]&bar=baz. But I am wondering if you need { allowEmptyArrays: true } when parsing because one can argue if the string has foo[] that means we want to be able to parse it to original object that was handed to qs.stringify. What do you think about dropping allowEmptyArrays option from the qs.parse?

Current behaviour is qs.parse('foo[]&bar=baz') -> { foo: [ '' ], bar: 'baz' }. After the above change it would produce { foo: [], bar: 'baz' }. I would guess that would be a breaking change where ''(empty string) is dropped?

ljharb commented 6 months ago

Yes, that would be a breaking change, and it’s important that things round trip - so i think we do need the option in both.

codecov[bot] commented 6 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Comparison is base (04f422f) 99.80% compared to head (f22b2bc) 99.81%.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #487 +/- ## ======================================= Coverage 99.80% 99.81% ======================================= Files 9 9 Lines 1543 1583 +40 Branches 177 183 +6 ======================================= + Hits 1540 1580 +40 Misses 3 3 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

konnng-dev commented 6 months ago

@ljharb any ETA to release a new version containing these changes?

ljharb commented 6 months ago

@konnng-dev there's a few open PRs i want to land first

mattsputnikdigital commented 5 months ago

Needs adding to the typescript definitions

Object literal may only specify known properties, and 'allowEmptyArrays' does not exist in type 'IStringifyOptions'.