How to deserialize query string into a JSON object with JavaScript?

Sometimes, we want to deserialize query string into a JSON object with JavaScript

In this article, we’ll look at how to deserialize query string into a JSON object with JavaScript.

How to deserialize query string into a JSON object with JavaScript?

To deserialize query string into a JSON object with JavaScript, we can use the URLSearchParams constructor.

For instance, we write:

const url = new URL('https://example.com?foo=1&bar=2');
const params = new URLSearchParams(url.search);
const obj = Object.fromEntries([...params])
console.log(obj)

to create a new URL instance with the URL string.

Then we create the URLSearchParams instance with the url.search property which has the query string.

Next, we spread params into an array of key-value pair arrays.

Finally, we use Object.fromEntries to convert the array into an object.

Therefore, obj is

{
  bar: "2",
  foo: "1"
}

Conclusion

To deserialize query string into a JSON object with JavaScript, we can use the URLSearchParams constructor.