Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Convert URL Parameters to JSON in JavaScript?
When working with URLs you will often encounter query parameters that add additional information to the base URL. It may be helpful for developers whenever they need to convert these URL parameters to JSON format, especially for reading and manipulating data. Here we will explore different methods to convert URL parameters to a JSON format in JavaScript including built-in methods and custom solutions using split, reduce, and regular expressions.
Understanding URL Parameters
URL parameters (query string) follow the ? character in a URL, with each key-value pair separated by &. Here's an example URL:
https://example.com/page?name=Pankaj&age=20&city=Surat
In this URL name=Pankaj, age=20, and city=Surat are query parameters.
Using URLSearchParams (Recommended)
The URLSearchParams interface provides built-in methods to work with query parameters. This is the simplest and most efficient way to parse URL parameters.
Example
function urlParamsToJson(url) {
try {
const urlObject = new URL(url);
const params = new URLSearchParams(urlObject.search);
let jsonObj = {};
params.forEach((value, key) => {
jsonObj[key] = value;
});
return jsonObj;
} catch (error) {
console.error('Invalid URL:', error.message);
return {};
}
}
const url = 'https://example.com/page?name=Pankaj&age=20&city=Surat';
console.log(urlParamsToJson(url));
{ name: 'Pankaj', age: '20', city: 'Surat' }
Using Split and Reduce Methods
For more control and browser compatibility, you can use the split method to separate parameters and reduce to build the JSON object.
Example
function urlParamsToJson(url) {
if (!url.includes('?')) return {};
const queryString = url.split('?')[1];
if (!queryString) return {};
return queryString.split('&')
.filter(param => param)
.reduce((acc, param) => {
const [key, value = ''] = param.split('=');
try {
acc[decodeURIComponent(key)] = decodeURIComponent(value);
} catch (e) {
acc[key] = value;
}
return acc;
}, {});
}
const url = 'https://example.com/page?name=Pankaj&age=20&city=Surat';
console.log(urlParamsToJson(url));
{ name: 'Pankaj', age: '20', city: 'Surat' }
Using Regular Expressions
For those familiar with regex, this method can help parse complex URL strings by targeting specific patterns.
Example
function urlParamsToJson(url) {
const regex = /[?&]([^=#]+)=([^]*)/g;
let jsonObj = {};
let match;
while ((match = regex.exec(url))) {
try {
jsonObj[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
} catch (e) {
jsonObj[match[1]] = match[2];
}
}
return jsonObj;
}
const url = 'https://example.com/page?name=Pankaj&age=20&city=Surat';
console.log(urlParamsToJson(url));
{ name: 'Pankaj', age: '20', city: 'Surat' }
Handling Edge Cases
Empty Parameters
const urlWithoutParams = 'https://example.com/page'; console.log(urlParamsToJson(urlWithoutParams));
{}
Duplicate Keys
For URLs with duplicate keys, you can store values as arrays:
function urlParamsToJsonWithArrays(url) {
try {
const urlObject = new URL(url);
const params = new URLSearchParams(urlObject.search);
let jsonObj = {};
params.forEach((value, key) => {
if (jsonObj[key]) {
jsonObj[key] = Array.isArray(jsonObj[key])
? [...jsonObj[key], value]
: [jsonObj[key], value];
} else {
jsonObj[key] = value;
}
});
return jsonObj;
} catch (error) {
return {};
}
}
const urlWithDuplicates = 'https://example.com/page?name=Pankaj&name=Neeraj&age=20';
console.log(urlParamsToJsonWithArrays(urlWithDuplicates));
{ name: ['Pankaj', 'Neeraj'], age: '20' }
Comparison
| Method | Browser Support | Complexity | Error Handling |
|---|---|---|---|
| URLSearchParams | Modern browsers | Simple | Built-in |
| Split & Reduce | All browsers | Medium | Manual |
| Regular Expression | All browsers | Complex | Manual |
Conclusion
URLSearchParams is the recommended approach for modern applications due to its simplicity and built-in URL decoding. For legacy browser support, use the split and reduce method with proper error handling.
