Skip to main content
Back to Blog

JSON to Query String: Simplifying API Requests

Turn JSON objects into GET query strings with correct encoding and array handling so your API URLs always work.

Kashyap Thakar
9 min
JSONAPIURLDevelopment
JSON to Query String: Simplifying API Requests

Modern web applications communicate constantly via APIs. While JSON is the standard for request bodies (POST/PUT), GET requests typically rely on query strings. Manually converting complex JSON objects into URL-encoded query parameters is tedious and easy to get wrong.

The Challenge with GET Requests

Unlike POST requests where you can simply send a JSON blob in the body, GET requests require parameters to be appended to the URL. This limits the data types we can send to essentially just strings.

// JSON input
{ "search": "query", "page": 1, "filters": { "date": "today", "status": ["active", "pending"] } }

Converting the above manually into a string involves several decisions that affect compatibility with your backend framework.

Handling Arrays: The Great Divide

There is no single standard for how arrays should be represented in a query string. Different server-side frameworks expect different formats:

1. Repeating Keys (Java/Spring, .NET)

The key is repeated for each value.

?status=active&status=pending

2. Bracket Notation (PHP, Rails, Node.js libraries)

Brackets explicitly denote an array.

?status[]=active&status[]=pending

3. Comma Separated (Custom/Simple)

Single key with values separated by a delimiter.

?status=active,pending

The Complexity of Nesting

Things get even messier with nested objects. Should filters.date become filters[date] or filters.date?

  • Bracket Notation: filters[date]=today (Standard in qs library)
  • Dot Notation: filters.date=today (used by some APIs and by property binding in some frameworks)
  • JSON Stringified: filters={"date":"today"} (the whole value is one JSON string, which must be percent-encoded exactly once. See below)

URL Encoding Essentials

A common mistake is concatenating strings without encoding. Special characters have reserved meanings in URLs:

  • & starts a new parameter
  • = separates key and value
  • # starts a fragment
  • (space) breaks the URL

If your search query is "Time & Tide", sending ?q=Time & Tide will be interpreted as two parameters: q="Time " and a second parameter named " Tide" with no value. Correct encoding Time%20%26%20Tide is mandatory.

Why Not Just Write One Line?

Writing your own serializer is possible (Object.keys(params).map(...)), but a quick version often misses edge cases such as null values, nesting, array format, and encoding. The sections below show what those edge cases look like and a serializer that handles them.

Common Serialization Libraries

JavaScript/TypeScript

  • URLSearchParams: Native browser API, but limited support for nested objects and arrays
  • qs: Popular npm package with extensive options for array and object serialization
  • query-string: Lighter alternative for parsing and stringifying flat query strings, with array format options

Python

  • urllib.parse.urlencode: Standard library, handles basic cases
  • requests: Popular HTTP library with built-in parameter handling

Real-World Examples

E-commerce Search Filters

Converting complex filter objects into query strings:


{
  "category": "electronics",
  "price": { "min": 100, "max": 500 },
  "brands": ["Samsung", "Apple"],
  "inStock": true
}
                    

Becomes (bracket notation, shown decoded): ?category=electronics&price[min]=100&price[max]=500&brands[]=Samsung&brands[]=Apple&inStock=true

API Pagination

Pagination and sorting options are often sent as query strings too:


{
  "page": 2,
  "limit": 20,
  "sort": { "field": "created_at", "order": "desc" }
}
                    

Becomes: ?page=2&limit=20&sort[field]=created_at&sort[order]=desc

What URLSearchParams Does with Objects

URLSearchParams is the right low-level tool for encoding, but it only understands flat string pairs. Hand it anything else and it quietly converts values with String():

new URLSearchParams({ tags: ["a", "b"] }).toString()
// "tags=a%2Cb"

new URLSearchParams({ a: null, b: undefined, c: true, d: 1, e: { x: 1 } }).toString()
// "a=null&b=undefined&c=true&d=1&e=%5Bobject+Object%5D"

An array becomes a comma-joined string, null and undefined become the literal text "null" and "undefined", and a nested object becomes [object Object]. None of these throw, so the bug only shows up when the server receives garbage. You need a small flattening step before handing data to URLSearchParams.

A Configurable Serializer in 20 Lines

This function flattens nested objects with bracket notation, skips null and undefined, and supports the four common array formats. It delegates all encoding to URLSearchParams:

function toQuery(obj, { arrayFormat = "repeat" } = {}) {
  const pairs = [];
  const walk = (val, key) => {
    if (val == null) return;
    if (Array.isArray(val)) {
      if (arrayFormat === "comma") { pairs.push([key, val.join(",")]); return; }
      val.forEach((v, i) => walk(v,
        arrayFormat === "brackets" ? `${key}[]` :
        arrayFormat === "index" ? `${key}[${i}]` : key));
    } else if (typeof val === "object") {
      for (const [k, v] of Object.entries(val)) walk(v, key ? `${key}[${k}]` : k);
    } else {
      pairs.push([key, String(val)]);
    }
  };
  walk(obj, "");
  return new URLSearchParams(pairs).toString();
}

Using the JSON from the start of this article, { search: "query", page: 1, filters: { date: "today", status: ["active", "pending"] } }, each format produces the following (shown decoded for readability):

arrayFormatResult for filters.status
repeatfilters[status]=active&filters[status]=pending
bracketsfilters[status][]=active&filters[status][]=pending
indexfilters[status][0]=active&filters[status][1]=pending
commafilters[status]=active,pending

The actual output has the brackets and commas percent-encoded: filters%5Bstatus%5D%5B%5D=active and filters%5Bstatus%5D=active%2Cpending. That is correct and equivalent, because servers decode keys before interpreting brackets. When you see %5B and %5D in a log, they are just [ and ]. The comma format has one catch: a value that itself contains a comma is indistinguishable from two values, so only use it when values cannot contain commas.

Values That Do Not Survive the Trip

Query strings carry only text, so type information is lost. The receiving side gets the string "1", not the number, and the string "false", not a boolean, and must convert them (frameworks often do this from a schema). Some specific cases:

  • Empty string vs. missing: with the serializer above, { c: "" } becomes c= (key present, empty value) while null and undefined are dropped. Servers differ on whether c= means "empty" or "absent", so decide deliberately.
  • Falsy values: 0 and false are kept (d=false&e=0). Beware of if (value) style filtering that would drop them.
  • Empty arrays: produce no pairs at all, so "filter by nothing" and "no filter" look identical.
  • Dates: a Date is an object with no enumerable keys, so the serializer above silently drops it. Convert with toISOString() first, which is also what JSON.stringify produces for dates.

The JSON-in-One-Parameter Alternative

When the structure is too deep for brackets, or the backend wants a JSON document anyway, serialize once and send the whole thing as a single encoded value. Reading it back is lossless, and types survive:

const j = JSON.stringify({ date: "today", status: ["active", "pending"] });

new URLSearchParams({ filters: j }).toString()
// "filters=%7B%22date%22%3A%22today%22%2C%22status%22%3A%5B%22active%22%2C%22pending%22%5D%7D"

JSON.parse(new URLSearchParams(new URLSearchParams({ filters: j }).toString()).get("filters"))
// { date: 'today', status: [ 'active', 'pending' ] }

The trade-offs are readability and size: every quote, brace, and colon is expanded to three characters by percent-encoding, so URLs grow fast. These URLs are also harder to cache and log meaningfully. Do not nest encoding by hand: set the raw JSON string and let URLSearchParams encode it once, or you will produce double-encoded values (see URL Encoding & Decoding).

Reading Repeated Keys on the Way Back In

Parsing is where array formats bite. URLSearchParams keeps every pair, but the common shortcut Object.fromEntries keeps only the last one, and get() returns only the first:

const p = new URLSearchParams("status=active&status=pending");

p.get("status")                // "active"
p.getAll("status")             // [ 'active', 'pending' ]
Object.fromEntries(p)          // { status: 'pending' }

[...new URLSearchParams("filters[date]=today&status[]=a&status[]=b").keys()]
// [ 'filters[date]', 'status[]', 'status[]' ]

The last example shows that URLSearchParams has no concept of brackets: status[] is just a key spelled with brackets. Expanding bracket notation back into nested objects is the job of your framework or a library such as qs, and the format you choose when serializing must match what that parser expects.

When Not to Use a Query String

Query strings are visible in browser history, server logs, proxies, and Referer headers, so do not put tokens or personal data in them. They are also limited in length (see The Art of URL Building), and deeply nested filters are a sign the request wants a body. Use a POST (or a search endpoint that accepts JSON) for large or sensitive payloads, and keep GET for cacheable, shareable, bookmarkable requests. For the broader picture of picking a format for data on the wire, see the guide to data serialization formats.

Try It Yourself

The JSON to Query String Converter turns a JSON object into a query string in your browser. Nested objects are flattened with bracket notation (price[min]=100), and a toggle switches between the percent-encoded and decoded form. Be aware of two behaviors that differ from the serializer above: arrays are written with indices (brands[0]=Samsung), and null values are written as the text null rather than dropped. If your backend expects another array format, use the serializer in this article or a library such as qs.

Frequently Asked Questions

How do I convert a JSON object to a query string in JavaScript?

For a flat object of strings, new URLSearchParams(obj).toString() is enough. For nested objects or arrays, flatten them into key and value pairs first (for example with bracket notation) and pass the pairs to URLSearchParams, or use a library such as qs.

How do you pass an array in a query string?

There is no universal standard. The common choices are repeated keys (a=1&a=2), brackets (a[]=1&a[]=2), indexed brackets (a[0]=1), and comma-separated values. Use whichever your backend framework parses, and document it for API consumers.

Can a GET request have a JSON body instead?

Technically a request body on GET is not forbidden by HTTP syntax, but its semantics are undefined, and many clients, proxies, and caches ignore or reject it. Browsers' fetch does not allow a body on GET. Use query parameters, or switch to POST when the payload is complex.

Why do I see %5B and %5D in my URLs?

They are the percent-encoded forms of [ and ]. Encoders such as URLSearchParams and encodeURIComponent escape brackets because [ and ] are reserved delimiters in URLs, and servers decode them before applying bracket notation, so a%5B%5D=1 and a[]=1 mean the same thing.

Written by

Spotted a mistake? Let me know