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 converting 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 splits, reduces, regular expressions.

Understanding URL Parameters

URL parameters follow ? 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.

Approaches to Convert URL Parameters to JSON

Using URLSearchParams

The URLSearchParams interface provides methods to work with query parameters, this is a simple and efficient way to parse URL parameters directly.

Syntax

const params = new URLSearchParams(url.search);
let jsonObj = {};
params.forEach((value, key) => {
    jsonObj[key] = value;
});

Example

In this example we use URLSearchParams to access each query parameter from URL, by looping over the parameters with .forEach, we populate a jsonObj with keys and values.

function parseQueryString(url) {
    if (!url) 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) {
                console.warn(`Failed to decode query parameter: ${param}`);
            }
            
            return acc;
        }, {});
}
const url = 'https://example.com/page?name=Pankaj&age=20&city=Surat';
console.log(parseQueryString(url));

Output

{
  "name": "Pankaj",
  "age": "20",
  "city": "Surat"
}

Using split and reduce Methods

For more control, you can use the split method to separate parameters and reduce to build of JSON objects.

Syntax

const queryString = url.split('?')[1];
const jsonObj = queryString.split('&').reduce((acc, param) => {
    const [key, value] = param.split('=');
    acc[key] = decodeURIComponent(value);
    return acc;
}, {});

Example

Here split method separates the query string from the URL, we then split each key-value pair by & and use reduce to iterate over these pairs, constructing jsonObj, each parameter is split into key and value with split('='), then assigned to jsonObj, the output JSON object matches parameters in URL.

function urlParamsToJson(url) {
    const queryString = url.split('?')[1];
    const jsonObj = queryString.split('&').reduce((acc, param) => {
        const [key, value] = param.split('=');
        acc[key] = decodeURIComponent(value);
        return acc;
    }, {});
    return jsonObj;
}
const url = 'https://example.com/page?name=Pankaj&age=20&city=Surat';
console.log(urlParamsToJson(url));

Output

{
  "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.

Syntax

const regex = /[?&]([^=#]+)=([^]*)/g;
let jsonObj = {};
let match;
while ((match = regex.exec(url))) {
    jsonObj[match[1]] = decodeURIComponent(match[2]);
}

Example

In this example we use regular expressions to match each search parameter in a URL, regex takes the following key-value pairs ? tor & and assign it to the jsonObj decodeURIComponent function, this helps ensure that encoded characters are decoded correctly, the final JSON object reflects URL parameters correctly.

function urlParamsToJson(url) {
    const regex = /[?&]([^=#]+)=([^]*)/g;
    let jsonObj = {};
    let match;
    while ((match = regex.exec(url))) {
        jsonObj[match[1]] = decodeURIComponent(match[2]);
    }
    return jsonObj;
}
const url = 'https://example.com/page?name=Pankaj&age=20&city=Surat';
console.log(urlParamsToJson(url));

Output

{
  "name": "Pankaj",
  "age": "20",
  "city": "Surat"
}

Handling Edge Cases

  • Empty Parameters: If a URL has no parameters (https://example.com/page), each method should ideally return an empty object {}.
const url = 'https://example.com/page';
// Expected output: {}
console.log(urlParamsToJson(url)); 
  • Duplicate Keys: If a URL contains duplicate keys (e.g. ?name=Pankaj&name=Neeraj), only last key-value pair will be retained, to store all values, consider storing duplicates as arrays.

  • Example Modification
    function urlParamsToJson(url) {
        const params = new URLSearchParams(url.split('?')[1]);
        let jsonObj = {};
        params.forEach((value, key) => {
            if (jsonObj[key]) {
                jsonObj[key] = [].concat(jsonObj[key], value);
            } else {
                jsonObj[key] = value;
            }
        });
        return jsonObj;
    }
    
    Updated on: 2024-11-05T11:11:41+05:30

    2K+ Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements