Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add filter/replacer fn option to stringify #203

Open
ashtonian opened this issue Aug 17, 2019 · 4 comments
Open

add filter/replacer fn option to stringify #203

ashtonian opened this issue Aug 17, 2019 · 4 comments

Comments

@ashtonian
Copy link

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;
}
@sindresorhus
Copy link
Owner

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.

@anarian
Copy link

anarian commented Apr 1, 2020

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"

@stralsi
Copy link

stralsi commented Apr 21, 2020

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.

@ekabolotina
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants