url-object-converter
v2.0.0
Published
A lightweight, zero-dependency package that converts JavaScript objects into URL-friendly query parameters and vice versa. Supports nested objects, arrays, Date, BigInt, and custom serializers.
Maintainers
Readme
url-object-converter
A lightweight, zero-dependency TypeScript package for converting JavaScript objects to URL query strings and vice versa. Supports nested objects, arrays, Date, BigInt, and custom serializers.
Features
- Zero dependencies - No external runtime dependencies
- Dual ESM/CommonJS - Works with both module systems
- TypeScript first - Full type definitions included
- Configurable - Multiple array formats, custom serializers/deserializers
- Type preservation - Automatically parses booleans, numbers, dates, null
- Nested structures - Deep object and array support
- Date & BigInt - Built-in handling for Date and BigInt types
- Sparse arrays - Preserves array holes during conversion
Installation
npm install url-object-converterQuick Start
import { convertObjectToUrl, convertUrlToObject } from 'url-object-converter';
// Object to URL
const url = convertObjectToUrl({
name: 'John',
age: 30,
active: true
});
// Result: 'name=John&age=30&active=true'
// URL to Object
const obj = convertUrlToObject('name=John&age=30&active=true');
// Result: { name: 'John', age: 30, active: true }API Reference
convertObjectToUrl(obj, options?)
Converts a JavaScript object to a URL-encoded query string.
Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| obj | object | The object to convert |
| options | ToUrlOptions | Optional configuration |
Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| encode | boolean | true | URL-encode the values |
| arrayFormat | 'bracket' \| 'index' \| 'comma' | 'bracket' | Array serialization format |
| skipNull | boolean | false | Skip null values |
| skipEmptyString | boolean | true | Skip empty string values |
| nestedDelimiter | string | '.' | Delimiter for nested objects |
| serializer | (value, key) => string \| undefined | - | Custom value serializer |
Examples
// Basic usage
convertObjectToUrl({ name: 'John Doe', age: 30 });
// 'name=John%20Doe&age=30'
// Nested objects
convertObjectToUrl({ user: { name: 'Alice', role: 'admin' } });
// 'user.name=Alice&user.role=admin'
// Arrays with bracket format (default)
convertObjectToUrl({ tags: ['js', 'ts'] });
// 'tags%5B0%5D=js&tags%5B1%5D=ts'
// Arrays with comma format
convertObjectToUrl({ tags: ['js', 'ts'] }, { arrayFormat: 'comma' });
// 'tags=js%2Cts'
// Arrays with index format
convertObjectToUrl({ tags: ['js', 'ts'] }, { arrayFormat: 'index' });
// 'tags.0=js&tags.1=ts'
// Date values
convertObjectToUrl({ created: new Date('2024-01-15T10:30:00Z') });
// 'created=2024-01-15T10%3A30%3A00.000Z'
// BigInt values
convertObjectToUrl({ bigNum: BigInt('9007199254740993') });
// 'bigNum=9007199254740993'
// Skip null values
convertObjectToUrl({ a: 'value', b: null }, { skipNull: true });
// 'a=value'
// Custom serializer
convertObjectToUrl({ price: 19.99 }, {
serializer: (value, key) => {
if (key === 'price') return `$${value}`;
return String(value);
}
});
// 'price=%2419.99'convertUrlToObject<T>(urlQueryString, options?)
Parses a URL query string into a JavaScript object.
Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| urlQueryString | string | The URL query string to parse |
| options | ToObjectOptions | Optional configuration |
Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| parseTypes | boolean | true | Parse type values (true/false/null/numbers) |
| arrayFormat | 'bracket' \| 'index' \| 'comma' \| 'auto' | 'auto' | Array parsing format |
| nestedDelimiter | string | '.' | Delimiter for nested objects |
| deserializer | (value, key) => unknown | - | Custom value deserializer |
Examples
// Basic usage
convertUrlToObject('name=John&age=30');
// { name: 'John', age: 30 }
// Type parsing (automatic)
convertUrlToObject('active=true&count=42&value=null');
// { active: true, count: 42, value: null }
// Disable type parsing
convertUrlToObject('active=true&count=42', { parseTypes: false });
// { active: 'true', count: '42' }
// Nested objects
convertUrlToObject('user.name=Alice&user.details.age=25');
// { user: { name: 'Alice', details: { age: 25 } } }
// Arrays (auto-detected)
convertUrlToObject('tags%5B0%5D=js&tags%5B1%5D=ts');
// { tags: ['js', 'ts'] }
// Comma-separated arrays
convertUrlToObject('tags=js,ts,node', { arrayFormat: 'comma' });
// { tags: ['js', 'ts', 'node'] }
// Date parsing
convertUrlToObject('created=2024-01-15T10:30:00.000Z');
// { created: Date('2024-01-15T10:30:00.000Z') }
// TypeScript generics
interface User { name: string; age: number }
const user = convertUrlToObject<User>('name=John&age=30');
// user.name and user.age are properly typed
// Custom deserializer
convertUrlToObject('price=1999', {
deserializer: (value, key) => {
if (key === 'price') return { cents: parseInt(value), formatted: `$${(parseInt(value) / 100).toFixed(2)}` };
return value;
}
});
// { price: { cents: 1999, formatted: '$19.99' } }Array Formats
The package supports three array formats:
| Format | Object | URL String |
|--------|--------|------------|
| bracket | { arr: [1, 2] } | arr[0]=1&arr[1]=2 |
| index | { arr: [1, 2] } | arr.0=1&arr.1=2 |
| comma | { arr: [1, 2] } | arr=1,2 |
Type Preservation
The convertUrlToObject function automatically parses:
| URL Value | JavaScript Value |
|-----------|-----------------|
| true | true (boolean) |
| false | false (boolean) |
| null | null |
| undefined | undefined |
| 42, -10 | 42, -10 (number) |
| 3.14 | 3.14 (number) |
| 2024-01-15T10:30:00.000Z | Date object |
Edge Cases
Sparse Arrays
// Converting
convertObjectToUrl({ arr: [1, , 3] });
// 'arr%5B0%5D=1&arr%5B2%5D=3'
// Parsing
convertUrlToObject('arr%5B0%5D=1&arr%5B2%5D=3');
// { arr: [1, undefined, 3] }Deeply Nested Structures
const obj = {
users: [
{ name: 'Alice', scores: [95, 87] },
{ name: 'Bob', scores: [88, 91] }
]
};
const url = convertObjectToUrl(obj);
const restored = convertUrlToObject(url);
// restored deeply equals objMigration from v1.x
Version 2.0 is mostly backward compatible. The main changes:
- New options parameter - Both functions now accept an optional
optionsobject - ESM by default - The package is now ESM-first with CommonJS support
- Node.js 18+ - Minimum Node.js version is now 18
// v1.x
convertObjectToUrl(obj);
convertUrlToObject(url);
// v2.x (same API, options are optional)
convertObjectToUrl(obj);
convertObjectToUrl(obj, { arrayFormat: 'comma' }); // New!
convertUrlToObject(url);
convertUrlToObject(url, { parseTypes: false }); // New!TypeScript
Full TypeScript support with exported types:
import {
convertObjectToUrl,
convertUrlToObject,
ToUrlOptions,
ToObjectOptions,
SerializableObject,
SerializableArray,
SerializableValue,
Primitive
} from 'url-object-converter';Browser Support
Works in all modern browsers that support ES2020. For older browsers, use a bundler with appropriate transpilation.
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT © Adarsh Pawar
