ljharb / qs

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

Stringify null values #462

Open tada5hi opened 1 year ago

tada5hi commented 1 year ago

It would be really great, if null values could be stringified via an option as a null string instead of an empty string. If that is fine for you @ljharb i would create a pull request for that.

Greetings Peter

ljharb commented 1 year ago

You can already do that with the encoder option.

tada5hi commented 1 year ago

good point, but i find is not very intuitive to use and feels like a bit of a overhead.

ljharb commented 1 year ago

Given that it's a pretty uncommon use case (you're the first to ask afaik) I don't think it's worth the complexity of an additional option. Can you elaborate on your use case?

tada5hi commented 1 year ago

i use it for a library (rapiq) which builds & parses an extended JSON-API Query String format and i plan to do a bigger refactoring & cleanup in the near feature and also want to reach v1.0.0. Therefore, the following should be possible: /?filter[parameter]=null and ?filter[parameter]=id1,id2,null

ljharb commented 1 year ago

Wouldn't there be a lot more things you'd need to handle to make query strings compatible with JSONAPI, such that you'd need the encoder/decoder anyways?

tada5hi commented 1 year ago

properly, yes.

ljharb commented 1 year ago

then what would be the benefit of the option, when it’s trivial to handle it in a decoder?

teobmg commented 1 year ago

@ljharb can you please provide an example? I'm trying to stringify in this way:

stringify(
          {
            division: ['', null],
          },
          {
            arrayFormat: 'brackets',
            strictNullHandling: true
          },
        )

And parse in this way

qs.parse(query, {
      decoder: (string, defaultDecoder) =>
        string === 'null' ? null : defaultDecoder(string),
      strictNullHandling: true,
    });

But debugging the decoder, the string that I receive as value is always '', so I'm not able to distinguish between a real empty string and a null value.

ljharb commented 1 year ago

@teobmg stringify gets a null, so the encoder would be what handles that - sorry for misspeaking. by the time it's parsed, everything's a string and there's no null.

In other words, you have to encode null specially, and then decode that specially.