GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Parse booleans & numbers · Issue #91 · ljharb/qs

Parse booleans & numbers #91

New issue
Copy link
New issue
Copy link
Closed
Closed
Parse booleans & numbers#91
Copy link
Assignees
nlf
Labels
discussionfeature requestparse

Description

@xpepermint
xpepermint
opened on May 27, 2015
Issue body actions
// now
Qs.parse('a=true');    // { a: 'true' }
Qs.parse('a=21.31');    // { a: '21.31' }
// but I would expect boolean
var obj = Qs.parse('a=true');    // { a: true }
Qs.parse('a=21.31');    // { a: 21.31 }

Currently I use express-query-boolean package which parses true and false strings into boolean but it would be great to have this feature included in qs.

Reacted by Byron Sargeant, Siraj Alam, Bhavan Kuchibhotla, Tristan Matthias, Antoine, Leandre, Alpeche Pancha, Alexander, Junyi, Léo Dupont and 13 more

Activity

Next
  1. xpepermint
    changed the title [-]Parse booleans[/-] [+]Parse booleans & numbers[/+] on May 27, 2015
  2. nlf
    added
    feature request
    on May 28, 2015
  3. nlf
    self-assigned this
    on May 28, 2015
  4. nlf commented on May 28, 2015

    @nlf
    nlf
    on May 28, 2015
    Collaborator
    More actions

    My current feeling is that this belongs elsewhere. There are so many conversion patterns that could take place that I don't really want to open the can of worms of implementing them all here. Unless there's a large demand for this, I'm going to say no.

    Leaving open for discussion, however.

    Reacted by Poyoman/Johan
  5. nlf
    added
    discussion
    on May 28, 2015
  6. xpepermint commented on May 28, 2015

    @xpepermint
    xpepermint
    on May 28, 2015
    Author
    More actions

    OK, I made a plugin for now https://github.com/xpepermint/query-types.

    Reacted by Vivek Suyambu, Ronan Jouchet, alexis and Lorand Horvath
  7. davidraleigh commented on Jun 1, 2015

    @davidraleigh
    davidraleigh
    on Jun 1, 2015
    More actions

    I think the @xpepermint request is valid. I was disappointed to see that this isn't a feature. That parse assumes all numbers are strings makes it not so helpful.

    Reacted by Robert Hall, Karl Lind, Shane Thacker, Matt H, Fey, Masahiko Kimura, Oleg Batuev, Tristan Matthias, Thinh Nguyen, Alpeche Pancha and 15 more
  8. travist commented on Jul 7, 2015

    @travist
    travist
    on Jul 7, 2015
    More actions

    This is actually a problem I am facing using the very popular https://github.com/request/request library. What I am running into is that my REST api is outputting booleans as true and false. However, when a PUT request is made, request.js uses this library to convert it to a string, which this then turns all of my booleans into strings breaking the app. I am curious why this library is converting booleans and numbers to strings. Its a pretty easy fix, and I am willing to submit a pull request.

  9. jdiaz5513 commented on Jul 9, 2015

    @jdiaz5513
    jdiaz5513
    on Jul 9, 2015
    More actions

    Part of me wants this too, but automatic type coersion here is troublesome. What if you wanted "true" as a string? Or "21.33" as a string? I often deal with currency amounts formatted as strings to avoid floating point precision loss.

    In particular if you're allowing user input to show up in the query string, all someone has to do is type in true where you were expecting a string and good luck avoiding a crash there.

    At least the current behavior is predictable and very well defined.

    Reacted by Nazar and Martin Bories
  10. travist commented on Jul 9, 2015

    @travist
    travist
    on Jul 9, 2015
    More actions

    Thanks for the information. I am no longer blocked by this, so I think I can get by without this change. I was actually able to get around this using https://github.com/visionmedia/superagent instead of https://github.com/request/request (which uses querystring for posts). I can only assume that superagent does not use query string method for posting information, but I have not dug deep enough yet to determine what is actually different. All I know is my JSON object is not altered from a GET to a PUT with superagent instead of request.js altering the JSON object by converting all numerics and booleans to strings. This nugget may prove helpful for anyone else running into this same issue with request.js.

  11. DesignByOnyx commented on May 5, 2016

    @DesignByOnyx
    DesignByOnyx
    on May 5, 2016
    Contributor
    More actions

    The plugin created by @xpepermint worked for me and will likely work for others who need it. I agree with the fact that I don't think qs should do this for you and people should opt in to this type coercion if they need it. For example, I have some string fields which are actually going to hold values such as "1456" some of the time. I know that the plugin will convert this to a number, but I also know that my data store will save it as a string - so this works for me. If my data store didn't do this, I wouldn't mind calling toString() on a few fields before saving.

  12. ljharb commented on Jul 21, 2016

    @ljharb
    ljharb
    on Jul 21, 2016
    Owner
    More actions

    I'm happy to consider a way for users to opt in to automatic coercion - but I wouldn't want that by default.

    I'm closing this for now, but am happy to reopen it if it warrants further discussion or work.

  13. ljharb
    closed this as completedon Jul 21, 2016
  14. malomick commented on Oct 19, 2016

    @malomick
    malomick
    on Oct 19, 2016
    More actions

    Could there not be some way of indicating coercion on a case-by-case basis, using a special character maybe? For example, we could have http://example.com/api/todos/?completed@=true&id@=1, and that would indicate that we want 'completed' and 'id' to be coerced, so we'd get { completed: true, id: 1 }... but if we just did completed=true&id@=1, then only id would be coerced, so we'd get { completed: 'true', id: 1 }.

    We could have the special character either in the property name, or in the value itself, and we could put it either at the beginning or the end (although I like it right up next to the = sign).

    [ update ]

    I've got the above implementation working here, at least for parsing... we might want to add some enforcement for the character(s) that can be chose to indicate coercion, which I currently have defaulting to @;

  15. ljharb commented on Oct 20, 2016

    @ljharb
    ljharb
    on Oct 20, 2016
    Owner
    More actions

    That seems very inelegant - you'd need to support that special character in your server code as well as your client code.

    In other words, there's no standard for using some kind of special character, so I think it'd be a very bad idea to codify that into qs.

  16. 39 remaining items

  17. sirajalam049 commented on Mar 16, 2020

    @sirajalam049
    sirajalam049
    on Mar 16, 2020
    More actions

    isn't it good to have an option as parseBool and parseNumber just like query-string have?

    Reacted by Mick Malowany, Temirlan Ismagulov, Vladyslav I, Ezra Celli, Leandro-Albano, alexis, n年级, Moon Cheung, Salah Eddine Ait Balkacm, Michael Harley and 5 more
  18. ljharb commented on Mar 16, 2020

    @ljharb
    ljharb
    on Mar 16, 2020
    Owner
    More actions

    That package's docs for parseBool say "if it's a boolean", and "if it's a number", but don't explicitly describe how they determine that. In some server frameworks, a boolean is yes/no/true/TRUE/false/FALSE/on/off/1/0. In others, it may just be true/false. In some, it might be cierto/falso, perhaps.

    In other words, having these options that arbitrarily encode one person's opinion about "how to determine them" is flawed at best, and I'd prefer not to have them at all. You can, however, use a custom decoder to decide for yourself what "it's a boolean" means, and then qs wouldn't run the likely risk of having nonsensical options.

    Reacted by Alex Laurent, Alan Gatticelli and hpawe01
    Reacted by Vladyslav I, Leandro-Albano, Hadi Aghandeh and Ville Saukkonen
  19. HadiAghandeh commented on Apr 8, 2021

    @HadiAghandeh
    HadiAghandeh
    on Apr 8, 2021
    More actions

    @ljharb
    on/off/1/0/yes/no are basically custom type of values which represent boolean and not converting to boolean is reasonable. And who ever is using then is most likely is checking their validity based on their type, which is not Boolean. So no argue on converting on/off/1/0/yes/no. But what would be the use of true/TRUE/false/FALSE as string other than representing a boolean value?

  20. ljharb commented on Apr 8, 2021

    @ljharb
    ljharb
    on Apr 8, 2021
    Owner
    More actions

    @HadiAghandeh https://www.engadget.com/icloud-true-last-name-lock-out-192224309.html

    Reacted by Nikita Skovoroda, Hadi Aghandeh, Ryan Wheale and benknab
    Reacted by David Ferreira, Raku Zeta and Stephan Nielsen
  21. DesignByOnyx commented on Apr 9, 2021

    @DesignByOnyx
    DesignByOnyx
    on Apr 9, 2021
    Contributor
    More actions

    The thing is, this type of "auto-coercion" code must be written to iterate over data and interpret certain fields as scalar/primitive values (numbers, booleans, etc). That code can be written in two places:

    1. The qs library can implement it - this would be a breaking change with guaranteed adverse affects. You have to worry about "how do I turn this off", which results in this library having more API, which means more maintenance/documentation, which leads to more "why is this happening" types of bugs, and a whole host of other potential issues.
    2. You can implement it yourself on a per-project basis - this give you full control over which values should be coerced, the qs library stays leaner and more predictable, and everybody is happy - even the developer who had to spend 15 minutes googling and copying code into their project.

    Option 2 is a clear winner hear. I propose that the docs should link to a code tried-and-true coercion snippet for easy copy/paste and lay this issue to rest.

    Reacted by Jordan Harband and Benjamin Schuch
  22. ljharb commented on Apr 9, 2021

    @ljharb
    ljharb
    on Apr 9, 2021
    Owner
    More actions

    Happy to accept PRs to improve the docs.

    Reacted by Ryan Wheale
  23. ljharb
    added a commit that references this issue on Apr 18, 2021

    [Docs] add note and links for coercing primitive values

    c2ae487
  24. SteveOscar commented on Jun 21, 2021

    @SteveOscar
    SteveOscar
    on Jun 21, 2021
    More actions

    @AndreiMotinga based off of #91 (comment):

    qs.parse(window.location.search, { ignoreQueryPrefix: true, arrayFormat: 'bracket', decoder(str, decoder, charset) {
      const strWithoutPlus = str.replace(/\+/g, ' ');
      if (charset === 'iso-8859-1') {
      // unescape never throws, no try...catch needed:
        return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
      }
    
      if (/^(\d+|\d*\.\d+)$/.test(str)) {
        return parseFloat(str)
      }
    
      const keywords = {
        true: true,
        false: false,
        null: null,
        undefined,
      };
      if (str in keywords) {
        return keywords[str]
      }
    
      // utf-8
      try {
        return decodeURIComponent(strWithoutPlus);
      } catch (e) {
        return strWithoutPlus;
      }
    } });

    Note that this check for floats (/^(\d+|\d*\.\d+)$/.test(str)) misses negative values. I'm working with lat/long and it bit me. I think this regex will work: /^[+-]?\d+(\.\d+)?$/

    Reacted by Florian Cäsar, Sang Au, Shravan Sunder, Martin Muzatko and Mateusz Leonowicz
  25. yiminlab commented on Aug 26, 2021

    @yiminlab
    yiminlab
    on Aug 26, 2021
    More actions

    Oh! I thank it's very helpful~ 👍

  26. ljharb
    added 3 commits that reference this issue on Jan 11, 2022

    [Docs] add note and links for coercing primitive values (#408)

    749a584

    [Docs] add note and links for coercing primitive values (#408)

    dbb54a8

    [Docs] add note and links for coercing primitive values (#408)

    29c8f3c
  27. jarraga commented on Mar 17, 2023

    @jarraga
    jarraga
    on Mar 17, 2023 · Hidden as outdated
    show commentMore actions
  28. tientran0019 commented on Nov 30, 2023

    @tientran0019
    tientran0019
    on Nov 30, 2023
    More actions

    It's work for me

    qs.parse(request.querystring, {
          decoder(str: string, defaultDecoder: qs.defaultDecoder, charset: string, type: 'key' | 'value') {
    	if (type === 'value' && /^(?:-(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))|(?:0|(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))))(?:.\d+|)$/.test(str)) {
    		return parseFloat(str);
    	}
    
    	const keywords = {
    		true: true,
    		false: false,
    		null: null,
    		undefined: undefined,
    	};
    	if (type === 'value' && str in keywords) {
    		return keywords[str];
    	}
    
    	return defaultDecoder(str, defaultDecoder, charset);
        }, 
    })
    Reacted by Crauzer, astrot1988 and ATS
    Reacted by VBV
  29. micobarac commented on Feb 17, 2025

    @micobarac
    micobarac
    on Feb 17, 2025
    More actions

    I extended https://github.com/xpepermint/query-types:

    query.middleware.ts

    import qs from 'qs';
    
    type ParsedValue = string | number | boolean | Date | Record<string, unknown> | unknown[];
    
    function isObject(val: unknown): val is Record<string, unknown> {
      return val !== null && typeof val === 'object' && val.constructor === Object;
    }
    
    function isNumber(val: unknown): boolean {
      return !isNaN(parseFloat(String(val))) && isFinite(Number(val));
    }
    
    function isBoolean(val: unknown): boolean {
      return val === 'false' || val === 'true';
    }
    
    function isDate(val: unknown): boolean {
      if (!(typeof val === 'string' || typeof val === 'number' || val instanceof Date)) return false;
      return !isNaN(new Date(val).getTime());
    }
    
    function isArray(val: unknown): val is unknown[] {
      return Array.isArray(val);
    }
    
    function isNestedArray(val: unknown): val is unknown[][] {
      return Array.isArray(val) && val.length > 0 && Array.isArray(val[0]);
    }
    
    function parseValue(val: unknown): ParsedValue | null {
      if (typeof val === 'undefined' || val === 'null' || val === '') {
        return null;
      } else if (isNumber(val)) {
        return parseNumber(val);
      } else if (isBoolean(val)) {
        return parseBoolean(val);
      } else if (isDate(val)) {
        return parseDate(val);
      } else if (isNestedArray(val)) {
        return val.map((arr) => parseArray(arr));
      } else if (isArray(val)) {
        return parseArray(val);
      } else if (isObject(val)) {
        return parseObject(val);
      } else {
        return val as string;
      }
    }
    
    function parseObject(obj: Record<string, unknown>): Record<string, ParsedValue> {
      const result: Record<string, ParsedValue> = {};
      for (const key in obj) {
        const val = parseValue(obj[key]);
        if (val !== null) result[key] = val;
      }
      return result;
    }
    
    function parseNumber(val: unknown): number {
      return Number(val);
    }
    
    function parseBoolean(val: unknown): boolean {
      return String(val) === 'true';
    }
    
    function parseDate(val: unknown): Date | string {
      const parsed = new Date(val as string | number | Date);
      return isNaN(parsed.getTime()) ? String(val) : parsed;
    }
    
    function parseArray(arr: unknown[]): ParsedValue[] {
      return arr.map((item) => parseValue(item)).filter((item): item is ParsedValue => item !== null);
    }
    
    function queryMiddleware(options?: qs.IParseOptions): (str: string) => Record<string, ParsedValue> {
      return function (str: string): Record<string, ParsedValue> {
        try {
          return parseObject(qs.parse(str, options));
        } catch (error) {
          console.error('Query parsing failed:', error);
          return {};
        }
      };
    }
    
    export { queryMiddleware };

    In my case, I use it in NestJS application.

    main.ts

    import { RequestMethod } from '@nestjs/common/enums';
    import { NestFactory } from '@nestjs/core';
    import { NestExpressApplication } from '@nestjs/platform-express';
    import { setupSwagger } from 'swagger';
    import { AppModule } from './app.module';
    import { queryMiddleware } from './core/middleware/query.middleware';
    
    async function bootstrap() {
      // https://docs.nestjs.com/migration-guide#express-v5
      const app = await NestFactory.create<NestExpressApplication>(AppModule);
      //app.set('query parser', 'extended');
      app.set('query parser fn', queryMiddleware()); // Custom middleware with extended types processing
    
      app.enableCors();
    
      app.setGlobalPrefix('api', {
        exclude: [{ path: 'health', method: RequestMethod.GET }]
      });
    
      setupSwagger(app);
    
      await app.listen(3000);
    }
    bootstrap();

    The middleware will take care of:

    undefined, null, empty, number, boolean, date, array ... query params.

    Reacted by Johan Tanta
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

  • @nlf
    nlf

Labels

discussionfeature requestparse

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

    You are visitor 01402792 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.