GeezerVison is showing github.com — Parse booleans & numbers · Issue #91 · ljharb/qs
Parse booleans & numbers #91Description// 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 Activitychanged the title [-]Parse booleans[/-] [+]Parse booleans & numbers[/+] on May 27, 2015nlf commented on May 28, 2015 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. xpepermint commented on May 28, 2015 Reacted by Vivek Suyambu, Ronan Jouchet, alexis and Lorand Horvath davidraleigh commented on Jun 1, 2015 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 travist commented on Jul 7, 2015 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. jdiaz5513 commented on Jul 9, 2015 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 travist commented on Jul 9, 2015 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. DesignByOnyx commented on May 5, 2016 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. ljharb commented on Jul 21, 2016 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. malomick commented on Oct 19, 2016 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 @; ljharb commented on Oct 20, 2016 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. sirajalam049 commented on Mar 16, 2020 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 ljharb commented on Mar 16, 2020 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 HadiAghandeh commented on Apr 8, 2021 @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? ljharb commented on Apr 8, 2021 Reacted by Nikita Skovoroda, Hadi Aghandeh, Ryan Wheale and benknab Reacted by David Ferreira, Raku Zeta and Stephan Nielsen DesignByOnyx commented on Apr 9, 2021 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:
- 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.
- 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 ljharb commented on Apr 9, 2021 Happy to accept PRs to improve the docs. SteveOscar commented on Jun 21, 2021
@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 yiminlab commented on Aug 26, 2021 Oh! I thank it's very helpful~ 👍 jarraga commented on Mar 17, 2023 tientran0019 commented on Nov 30, 2023 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 micobarac commented on Feb 17, 2025 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.
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|