query-string icon indicating copy to clipboard operation
query-string copied to clipboard

add filter/replacer fn option to stringify

Open ashtonian opened this issue 6 years ago • 4 comments

It would be nice to enable a generic fn that can be used to hack add customize use cases

function filterFunc(key, value) {
   if (key == 'b') {
       // Return an `undefined` value to omit a property.
       return;
   }
   if (key == 'e[f]') {
       return value.getTime();
   }
   if (key == 'e[g][0]') {
       return value * 2;
   }
   return value;
}

ashtonian avatar Aug 17 '19 03:08 ashtonian

Can you present some actual use-cases? It's hard to see the value of this with the above example as it doesn't really make sense.

sindresorhus avatar Aug 31 '19 08:08 sindresorhus

One use case I came across, trying to pass a date as a parameter in the query string, and the web server is expecting an ISO date string (for example ASP.NET Core).

import * as qs from 'query-string';

const parameters = {
  after: new Date(Date.now())
}
const query = qs.serialize(parameters);
// query: "after=Wed%20Apr%2001%202020%2015%3A29%3A51%20GMT-0400%20(Eastern%20Daylight%20Time)"

Our work-around was to just wrap the usage of the serialize to handle this case:

function serializeQuery(params) {
  const toSerialize = {};
  Object.entries(values).forEach(([key, value]) => {
    if (value instanceof Date) {
      toSerialize[key] = value.toISOString();
    } else {
      toSerialize[key] = value;
    }
  });
  return qs.serialize(toSerialize);
}
const secondQuery = serializeQuery(parameters);
// secondQuery: "after=2020-04-01T19%3A29%3A51.714Z"

anarian avatar Apr 01 '20 19:04 anarian

I found this while looking for a way to specify how dates are serialized. I'm surprised to find out toISOString is not the default way dates are serialized. I assume that may be because not all parsers would correctly parse this format? If that is the case, some support for specifying date format in the library, as proposed here, would be welcome.

stralsi avatar Apr 21 '20 09:04 stralsi

I also faced with the same issue: date is being serialized incorrectly. It would be nice to add a special parameter of how to serialize dates. Or better add an optional serialize function.

ekabolotina avatar Sep 27 '23 06:09 ekabolotina