qs icon indicating copy to clipboard operation
qs copied to clipboard

Stringify null values

Open tada5hi opened this issue 2 years ago • 9 comments

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

tada5hi avatar Jan 15 '23 22:01 tada5hi

You can already do that with the encoder option.

ljharb avatar Jan 15 '23 23:01 ljharb

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

tada5hi avatar Jan 16 '23 10:01 tada5hi

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?

ljharb avatar Jan 16 '23 20:01 ljharb

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

tada5hi avatar Jan 18 '23 09:01 tada5hi

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?

ljharb avatar Jan 18 '23 17:01 ljharb

properly, yes.

tada5hi avatar Jan 21 '23 13:01 tada5hi

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

ljharb avatar Jan 21 '23 20:01 ljharb

@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.

teobmg avatar Aug 01 '23 07:08 teobmg

@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.

ljharb avatar Aug 04 '23 23:08 ljharb