A response that refuses to parse
The first sign that you are dealing with a guarded payload is usually a parser error at offset zero. A client calls an endpoint, the status line says 200, the headers include Content-Type: application/json, and the body begins like this:
)]}'
[["51.5074","-0.1278","London, United Kingdom"],
["40.7128","-74.0060","New York, United States"]]
The first four characters — )]}' — are not a JSON value of any kind. Strict parsers stop immediately: Python raises a JSONDecodeError at line 1, column 1, and JavaScript throws a SyntaxError before any data is touched. The instinctive conclusion is that the response is corrupted or that the API is misconfigured. Neither is true. That opening line is a deliberate security measure known as an anti-XSSI prefix, and everything after it is ordinary, valid JSON that parses without complaint once the guard is removed.
This article explains where the prefix comes from, why it looks the way it does, and how to inspect such a payload safely: identify the guard, remove exactly the guard, validate the remainder, and keep the original bytes intact while you do it.
Why the prefix exists: the JSON hijacking era
To understand the guard, you have to go back to the way browsers handled cross-site requests in the late 2000s. When a page on an attacker's site embeds a resource from another origin using a script tag, the browser fetches that resource and sends the user's cookies along with the request, because cookies ride on every request to a domain regardless of which page asked for them. The fetched content is then handed to the JavaScript engine and executed in the context of the attacker's page.
For HTML responses that would be useless — a script tag cannot make markup execute as data. But a JSON response was a different matter. In the JavaScript of that era, a top-level JSON array was a legal script statement, and the language allowed constructors and property accessors to be redefined. An attacker could redefine the behavior of arrays so that every element created during script execution was passed to attacker-controlled code. The sequence was quietly devastating: include the victim's API endpoint in a script tag, the victim's browser attaches session cookies, the response executes as script, and every JSON value inside it flows into the attacker's functions. The attacker's page never needed to read the response body directly; the data delivered itself.
The defense that emerged is beautifully simple: make the body impossible to execute. A response that starts with )]}' is a syntax error in the very first characters of the script, so nothing ever runs and no data reaches attacker code. The attacker still receives the bytes over the network, but the script engine rejects them outright, and the same-origin policy prevents the attacker's page from reading the body of the failed load as text. The guard converts a data leak into a harmless parse failure.
It is worth noting which payloads were exposed. A top-level JSON array was the ideal target, because arrays were the easiest construct to weaponize through constructor overrides, but object literals could be dangerous as well under certain browser behaviors. Payloads that already began with something a script engine could not tolerate — a bare string, a number, or a document written for another content type — were partially protected by accident. The guard made that protection explicit and universal: every response from a sensitive endpoint got the same hostile opening line, regardless of what shape its data took, so the safety of the endpoint no longer depended on the details of its schema.
Commonly seen guard patterns
The exact form of the prefix varies between services, but the idea is constant: pick characters that are cheap to add, easy to detect, and guaranteed to break script execution at the first token. Commonly seen patterns include a four-character combination such as )]}' — a large search company has used this form on several of its public endpoints for well over a decade — as well as loop statements that would run forever if executed, which a large social platform famously placed at the front of its responses, throw statements paired with a marker comment, and comment wrappers around the entire body. The table below summarizes the patterns you are most likely to meet and how each one should be handled during inspection.
| Opening pattern | Purpose | Handling during inspection |
|---|---|---|
)]}' | Four characters that cannot start a JavaScript statement, so a script-tag include fails on the first token | Strip the first line, then parse |
while(1); | If executed, loops forever and never evaluates the payload | Strip the first line, then parse |
for(;;); | Alternate infinite loop with the same effect | Strip the first line, then parse |
throw 1; plus a marker comment | Raises immediately when executed; the marker makes the guard easy to detect | Remove everything up to and including the marker |
/*-secure-*/ | Comment wrapper that breaks the top-level value out of statement position | Remove the comment before parsing |
Two properties matter more than the specific characters. First, the guard is stable: a service that uses )]}' today used it five years ago, so you can maintain a fixed list rather than guessing per request. Second, the guard is unambiguous: no legitimate JSON value can begin with any of these sequences, which makes detection reliable.
The inspection problem
Guarded payloads create an awkward situation for tooling. Every strict parser rejects the prefix, so a naive paste into a debugger or a quick script fails before it shows you anything useful. The response looks broken in the browser's network panel preview, in command-line tools, and in language runtimes alike:
>>> json.loads(body)
Traceback (most recent call last):
...
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The error is accurate — char 0 really is not valid JSON — but it tells you nothing about the guard sitting one line above the data. Command-line tools are no friendlier:
$ jq . response.txt
parse error: Invalid numeric literal at line 1, column 1
The temptation at this point is to reach for a lenient parser — a setting that tolerates leading garbage, a regex that grabs everything between the first bracket pair, or a JSON5-style extension that happily ignores stray tokens. Resist it. Lenient parsing cannot distinguish a guard from a corrupted first line of data, so it silently accepts payloads that a strict parser would have flagged, and it teaches you nothing about the exact boundary between guard and document. The whole point of inspection is to know precisely what the server sent; a parser that forgives structure is the wrong instrument for that job.
So the inspection workflow always has the same shape: recognize the guard, strip it, parse what remains, and be certain that nothing except the guard was removed. Each of those steps can be made mechanical, and the rest of this article walks through them in order.
Identifying the guard
Identification is the step where care pays off. The most robust rule is positional: the guard is the first line of the body, everything before the first newline. Read exactly that range, compare it against your list of known constants, and treat a mismatch as a finding rather than as something to work around. A payload whose first line is not a known guard may be an error page, an HTML login redirect, a body with a different guard convention, or genuinely corrupt data — each of those deserves different handling, and a blind strip destroys the evidence you need to tell them apart.
Position matters because guards differ in form. A loop-based guard reads just as clearly on the first line as the four-character form:
while(1);
{"users": [{"id": 1041, "name": "ada"}, {"id": 1042, "name": "lin"}]}
Both bodies follow the same rule: exactly one guard line, exactly one newline, then the document. When you see a second line that is neither guard nor data — or a guard that repeats — stop and investigate before parsing, because the body no longer matches the contract you are inspecting against.
Keep the candidate list small and explicit. The patterns in the table above are enough for most work. If you control the API, document the guard so that clients never have to infer it. If you do not control it, verify against real responses once and rely on the stability of the pattern thereafter. Beware of overly clever detection, such as scanning the first few lines for anything that does not look like JSON; guards are single lines by design, and a detector that consumes a variable amount of the body will eventually eat real data.
The guard occupies exactly one line. If your stripping logic removes more than the first line — or more than the documented constant — you are not cleaning the payload, you are deleting evidence. Keep the raw bytes next to the parsed result so any discrepancy stays visible.
Removing exactly the guard
Once the guard is identified, removal should be a slice, not a search. Cut at the first newline and keep the offset arithmetic explicit so that the amount removed is auditable. The following example shows the pattern in JavaScript:
const GUARDS = new Set([")]}'", "while(1);", "for(;;);"]);
const raw = await res.text();
const nl = raw.indexOf("\n");
const first = nl === -1 ? raw : raw.slice(0, nl);
if (!GUARDS.has(first)) {
throw new Error("Unexpected first line: " + first);
}
const data = JSON.parse(raw.slice(nl + 1));
The same logic in Python:
import json
GUARDS = {")]}'", "while(1);", "for(;;);"}
first_line, sep, rest = raw.partition("\n")
if first_line not in GUARDS or not sep:
raise ValueError(f"Unexpected first line: {first_line!r}")
data = json.loads(rest)
Both versions fail closed. If the first line is not a recognized guard, they raise instead of parsing, which means an unexpected body shape is always surfaced loudly rather than silently processed. Notice also what the code does not do: it never scans for the guard somewhere in the middle of the body, and it never strips anything when the first line already looks like JSON. A body without a guard is simply a body without a guard; treating that case as normal is how double-stripping bugs are born.
Verifying nothing else was stripped
Stripping is only safe if you can account for every byte removed. Three checks cover nearly all mistakes. First, length: the number of characters removed should equal the length of the guard line plus its newline, and asserting that makes off-by-one errors impossible to miss. Second, structure: after parsing, confirm that the top-level shape matches what the endpoint is documented to return — an array here, an object with particular keys there. A parser succeeding on half a document is the classic symptom of having stripped a real line of data. Third, content spot checks: compare a recognizable value against the raw body, such as verifying that the last identifier visible in the raw text also appears in the parsed result.
These checks sound bureaucratic, but each one has caught real incidents. Payloads have gained a second line, guards have been updated to a new constant, and transfer layers have mangled newlines — every one of those produced a plausible-looking parse of a truncated document until someone compared the raw bytes with the parsed result. Reading line-and-column parser errors helps here too: a parse failure at line 1, column 1 after stripping usually means the guard was not fully removed, while a failure on a later line points at the actual data.
The security flip side
Everything above describes stripping for inspection, and it is worth stating plainly why the stripping must stop there. The guard only protects while it is present in the response as delivered by the server. A browser that received a de-guarded body would once again be exposed to the cross-site scenarios described earlier — the whole mechanism depends on the bytes crossing the network in their guarded form. So the rule for production code is the mirror image of the inspection rule: keep the prefix in transit, strip only after receipt, and never ask the API team to remove the guard because your client finds it inconvenient.
Stripping belongs in client and inspection code only. A proxy or gateway that removes the guard before the response leaves your infrastructure reopens the exact hole the guard was installed to close — and it does so for every downstream consumer, not just your own tools.
If you control the API, the guidance runs the other way: add the guard if it is absent, especially when responses can be top-level JSON arrays. The cost is one short line and a documented convention; the benefit is an entire class of legacy cross-site attacks neutralized by default. Combine it with X-Content-Type-Options: nosniff so that browsers refuse to interpret a JSON response as anything other than JSON, and with CORS restrictions that keep cross-origin pages from reading response bodies at all.
Why the prefix persists anyway
It is fair to ask whether any of this still matters. The original attack relied on language features that no longer exist. ECMAScript 5, standardized in 2009, changed how arrays and objects are constructed in ways that defeat the constructor-override tricks, and it introduced JSON.parse as the sanctioned way to turn text into data. Modern browsers apply same-origin policy to script results more strictly, and CORS ensures that a cross-origin page cannot read a response unless the server explicitly permits it. Server-side protections have kept pace: fetch metadata headers such as Sec-Fetch-Dest let an API see exactly why the browser is requesting a resource and reject requests whose destination is a script tag rather than the application's own fetch call.
The prefix persists for unglamorous reasons. Old clients still exist and still expect it; removing it would break them. It costs nothing, and it functions as defense in depth — a second lock on a door that already has good locks, useful precisely on the day one of the better locks fails. There is also a compatibility corridor: countless parsing wrappers strip a known guard before delegating to a strict parser, so a service that drops the guard does not merely enable an old attack, it also breaks every one of those wrappers at once. The rational choice for a service is to keep the guard forever, and the rational choice for tooling is to understand it.
A checklist
- Confirm the body really is guarded: the first line, up to the first newline, matches a known guard constant.
- Reject unknown prefixes loudly instead of stripping speculatively.
- Strip precisely the guard line and its newline; assert the byte count removed.
- Parse the remainder with a strict parser and check the top-level shape against the endpoint's documented contract.
- Spot-check a recognizable value against the raw bytes to confirm no data line was consumed.
- In production request paths, keep the guard intact and strip only after receipt, client-side.
- Log what was stripped, and keep the raw body available until the parsed result has been verified.
Test it yourself
Open the JSON Inspector, paste the prefixed body from the first example, and watch the parser reject it. Delete the first line, paste the remainder, and confirm that the same bytes now parse cleanly — that contrast is the entire phenomenon in one experiment. Then go one step further: add a second guard line and see that a careless strip-everything-before-the-first-brace routine breaks, while a strip-the-first-line routine still succeeds. Related field notes round out the picture: how JSON travels in HTTP headers, what Problem Details error bodies look like, and how to decode line-and-column error messages when a stripped body still refuses to parse.
Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.