Query String to JSON Converter
Parse URL query strings into structured JSON objects with type coercion and duplicate key array aggregation.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
What is Query String to JSON Parsing?
Query String to JSON Parsing is the algorithmic deconstruction and decoding of URL query parameter strings into structured, typed JavaScript Object Notation (JSON) objects. In web application engineering, RESTful API architecture, digital marketing telemetry (Google Analytics UTM tags), and Single Page Application (SPA) state persistence, communication over the HTTP protocol frequently relies on transmitting serialized state within the URL query segment:
https://example.com/search?category=audio&filter[brand]=Sony&tags[]=bluetooth&tags[]=wireless&page=2&inStock=true
While native browser runtimes provide the standard URLSearchParams API, URLSearchParams is strictly flat: it treats keys as literal strings and cannot reconstruct nested object hierarchies (filter[brand]=Sony) or automatically group repeated bracket parameters into typed JavaScript arrays. Furthermore, native APIs treat all values as plain strings—failing to coerce "true" into a boolean or "2" into a number.
The Affi-Chain Query String to JSON Parser provides instant, 100% in-browser deserialization. It parses deep bracket notation, reconstructs nested object trees, groups array indices, auto-coerces numbers and booleans, and prevents prototype pollution exploits with zero network latency.
Query String Syntax Notations & Deserialization Matrix
Because URL parameters lack a universal typing specification, modern web frameworks (such as Express.js (qs), Ruby on Rails, Laravel, and Spring Boot) employ distinct parameter conventions:
| Query String Pattern | Syntactic Convention | Decoded JSON Output | Framework / Library Alignment |
|---|---|---|---|
| Flat Key-Value | ?q=laptop&limit=10 | {"q": "laptop", "limit": 10} | Standard URLSearchParams, Python parse_qs |
| Nested Brackets | ?user[name]=Alex&user[age]=30 | {"user": {"name": "Alex", "age": 30}} | Express.js (qs), Ruby on Rails, PHP |
| Array Brackets | ?color[]=red&color[]=blue | {"color": ["red", "blue"]} | PHP, Laravel, jQuery AJAX, Axios |
| Indexed Array | ?items[0]=A&items[1]=B | {"items": ["A", "B"]} | Express.js strict array parsing |
| Repeated Keys | ?tag=news&tag=tech | {"tag": ["news", "tech"]} | Django, Go net/url, AWS API Gateway |
| Comma Delimited | ?roles=admin,editor | {"roles": ["admin", "editor"]} | OpenAPI 3.0 / Swagger array serialization |
Step-by-Step Practical Transformation Example
Let us examine how a complex, nested e-commerce filter query string is parsed into a strongly typed JSON payload:
Raw Input URL Query String:
?search=Noise%20Cancelling&filters[brand]=Sony&filters[maxPrice]=350.00&tags[]=audio&tags[]=wireless&page=1&inStock=true&promoCode=null
Parsed Typed JSON Object:
{
"search": "Noise Cancelling",
"filters": {
"brand": "Sony",
"maxPrice": 350,
},
"tags": [
"audio",
"wireless"
],
"page": 1,
"inStock": true,
"promoCode": null
}
Practical Code Implementation: In-Browser Query String Parser
Below is a complete JavaScript parser that handles deep bracket hierarchies, array grouping, safe percent-decoding, and type coercion while protecting against prototype pollution:
/**
* In-Browser Deep Query String to JSON Deserializer.
*/
function queryStringToJson(queryString) {
if (!queryString || typeof queryString !== 'string') return {};
// Strip leading '?' or '#'
const cleanQuery = queryString.replace(/^[?#]/, '');
if (!cleanQuery) return {};
const result = Object.create(null); // Pure dictionary without Object.prototype
const pairs = cleanQuery.split('&');
for (const pair of pairs) {
if (!pair) continue;
const [rawKey, rawVal = ''] = pair.split('=');
// Decode percent-encoded components safely
const key = safeDecodeUri(rawKey.replace(/\+/g, ' '));
const val = safeDecodeUri(rawVal.replace(/\+/g, ' '));
const typedVal = coerceType(val);
// Parse nested path segments: user[address][city] -> ["user", "address", "city"]
const path = key.replace(/\]/g, '').split('[');
setDeepProperty(result, path, typedVal);
}
return result;
}
function safeDecodeUri(str) {
try {
return decodeURIComponent(str);
} catch {
return unescape(str);
}
}
function coerceType(val) {
if (val === 'true') return true;
if (val === 'false') return false;
if (val === 'null') return null;
if (val === 'undefined') return undefined;
if (!isNaN(val) && val.trim() !== '') return Number(val);
return val;
}
function setDeepProperty(target, path, value) {
let current = target;
for (let i = 0; i < path.length; i++) {
let segment = path[i];
// Security: Block Prototype Pollution attacks
if (segment === '__proto__' || segment === 'constructor' || segment === 'prototype') {
return;
}
const isLast = i === path.length - 1;
if (isLast) {
if (segment === '') {
// Array append notation: tags[]=a
const parentKey = path[i - 1];
if (!Array.isArray(current)) current = [];
current.push(value);
} else if (current[segment] !== undefined) {
// Merge repeated keys into an array
if (!Array.isArray(current[segment])) {
current[segment] = [current[segment]];
}
current[segment].push(value);
} else {
current[segment] = value;
}
} else {
const nextSegment = path[i + 1];
const isNextArray = nextSegment === '' || /^\d+$/.test(nextSegment);
if (current[segment] === undefined) {
current[segment] = isNextArray ? [] : {};
}
current = current[segment];
}
}
}
// Verification Example:
const testUrl = "page=2&sort=asc&filter[active]=true&filter[price]=99.95&tags[]=web&tags[]=dev";
console.log(JSON.stringify(queryStringToJson(testUrl), null, 2));
Comparison Matrix: Query Parsing Technologies
| Tool / Library | Deep Bracket Parsing? | Type Coercion ("true" → true) | Array Grouping | Prototype Pollution Protection |
|---|---|---|---|---|
| Affi-Chain Query Parser | Yes (filter[k]=v) | Yes (Native auto-cast) | Yes (tags[]) | 100% Built-in Protection |
Native URLSearchParams | No (Flat keys only) | No (All strings) | No (Requires manual .getAll()) | N/A |
Node.js qs package | Yes | Optional | Yes | Requires strict settings |
Python urllib.parse | No (Flat keys only) | No | Yes (Returns list per key) | N/A |
Critical Edge Cases & Common Parsing Traps
1. Prototype Pollution Vulnerabilities
A critical security vulnerability exists in naive recursive query string parsers. An attacker can craft malicious query parameters targeting JavaScript prototype chains:
https://example.com/api?__proto__[isAdmin]=true&constructor[prototype][status]=hacked
If the parser does not sanitize __proto__, constructor, and prototype, the attacker injects properties directly into the global Object.prototype, escalating privileges and causing remote code execution across the application.
- Universal Fix: Always reject keys named
__proto__,prototype, orconstructor, or store properties inside pure dictionaries created withObject.create(null).
2. Malformed Percent-Encoding (URIError: URI malformed)
If a query string contains an unencoded percent sign (e.g., ?discount=20%off), JavaScript's native decodeURIComponent() throws a fatal runtime exception:
URIError: URI malformed
A production parser must wrap decoding calls inside try/catch fallback blocks to prevent breaking on malformed strings.
3. Plus Sign (+) Space Interpretation
In URL query strings formatted by HTML form submissions, spaces are encoded as plus signs (+). Naive decoding via decodeURIComponent() does not convert + to spaces (it treats + literally). Always execute .replace(/\+/g, ' ') prior to percent-decoding.