JavaScript Object to Query String Encoding: From Basic Implementation to Modern APIs

Nov 08, 2025 · Programming · 13 views · 7.8

Keywords: JavaScript | Query String | URL Encoding | URLSearchParams | Object Serialization

Abstract: This article provides an in-depth exploration of encoding JavaScript objects into query strings, covering traditional manual implementations and the modern URLSearchParams API. Through detailed code examples, it analyzes basic encoding, recursive object handling, character escaping mechanisms, and browser compatibility, offering comprehensive solution comparisons and practical guidance.

Introduction

In web development, encoding JavaScript objects into query strings is a common requirement, particularly when constructing GET requests. As part of URLs, query strings must adhere to specific encoding rules to ensure proper data transmission and parsing. Based on high-scoring Stack Overflow answers and MDN documentation, this article systematically analyzes methods for encoding objects to query strings in JavaScript.

Basic Query String Encoding

The simplest encoding approach involves iterating over object properties and concatenating key-value pairs. The following function implements this process:

function serialize(obj) {
  var str = [];
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  }
  return str.join("&");
}

// Example usage
console.log(serialize({
  foo: "hi there",
  bar: "100%"
}));
// Output: foo=hi%20there&bar=100%25

The core logic of this function is: iterate over the object's own properties, encode each key and value using encodeURIComponent, and join them with & symbols. This method is straightforward but only suitable for flat objects.

Recursive Object Encoding

For nested objects, recursive processing is required. The following extended version supports complex data structures:

function serialize(obj, prefix) {
  var str = [], p;
  for (p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p;
      var v = obj[p];
      str.push((v !== null && typeof v === "object") ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
}

// Example usage
console.log(serialize({
  foo: "hi there",
  bar: {
    blah: 123,
    quux: [1, 2, 3]
  }
}));
// Output: foo=hi%20there&bar%5Bblah%5D=123&bar%5Bquux%5D%5B0%5D=1&bar%5Bquux%5D%5B1%5D=2&bar%5Bquux%5D%5B2%5D=3

This implementation uses PHP-style array notation for nested structures. When encountering objects or arrays, it recursively calls itself to build hierarchical key names.

Modern API: URLSearchParams

Modern browsers provide the URLSearchParams interface, simplifying query string operations:

// Create directly from object
const params = new URLSearchParams({
  foo: "hi there",
  bar: "100%"
});
console.log(params.toString());
// Output: foo=hi+there&bar=100%25

// Or use chained operations
const searchParams = new URLSearchParams();
searchParams.append("foo", "hi there");
searchParams.append("bar", "100%");
console.log(searchParams.toString());
// Output: foo=hi+there&bar=100%25

URLSearchParams automatically handles encoding and supports various data manipulation methods like append, delete, and get. Note that it encodes spaces as + rather than %20.

Encoding Mechanism Details

Query string encoding follows the application/x-www-form-urlencoded format. Key encoding rules include:

The encodeURIComponent function encodes all characters except letters, numbers, and - _ . ! ~ * ' ( ), making it suitable for query parameter values.

Browser Compatibility Considerations

URLSearchParams has been widely supported since 2018, but older browsers require polyfills or manual implementations. Manual encoding methods offer better compatibility but require handling edge cases manually.

Practical Recommendations

When choosing an encoding method, consider:

Conclusion

JavaScript offers multiple methods for encoding objects into query strings, ranging from basic manual implementations to modern URLSearchParams APIs. Developers should choose appropriate solutions based on project requirements and browser support. Understanding encoding mechanisms and compatibility considerations helps build robust web applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.