Security••11 min read

JSON Security Best Practices: A Checklist for Production

Real attacks against JSON-handling code and how to defend. Prototype pollution, billion laughs, JSON injection, JWT secrets, and validation patterns.

By JSONEditor.net Team

Attacks at parse time

The parser itself is rarely the attack target — JSON.parse in V8, SpiderMonkey, and JavaScriptCore has been audited for decades. What attackers go after is the surrounding code that loads, allocates, and processes the result.

Resource exhaustion. A 1 KB payload of {"a":{"a":{"a":... nested two thousand levels deep parses successfully and then crashes any recursive code that walks the tree. The fix is twofold: cap the input size with express.json({ limit: '100kb' }) or its equivalent in your framework, and use iterative tree traversal instead of recursion when you do not control the depth.

Memory blowup. Parsing a 100 MB JSON document allocates roughly 400 MB of objects in V8. If your server accepts uncapped JSON bodies, a single request can OOM the process. Set a sane body limit on every endpoint that takes JSON.

Hash collisions. Older JSON parsers stored object keys in hash tables vulnerable to collision attacks (CVE-2011-4815 and family). A crafted payload of thousands of keys that all hash to the same bucket turned O(n) parsing into O(n²). Modern engines randomise hash seeds; you are safe unless you are on a 2012-era runtime.

JSON injection in HTML and SQL

A string that parses as valid JSON can still contain attack payloads. {"name": "<script>alert(1)</script>"} is perfectly legal JSON. The XSS is on the page that renders name into HTML without escaping.

The classic mistake is embedding server-rendered JSON in a page like this:

<script>
  window.user = ${JSON.stringify(user)};
</script>

If user.name contains </script><script>steal()</script>, the page is owned. JSON.stringify does not escape < or >. The fix is to replace <, >, and & in the JSON output before injecting, or use JSON.parse(document.getElementById('data').textContent) with the data inside a <script type="application/json"> block (which is not executed and has different parsing rules).

SQL injection via JSON happens when you store JSON in a string column and build queries by concatenation. Use parameterised queries or your driver's typed JSON support — Postgres jsonb, MySQL JSON columns. Never string-interpolate JSON into a SQL statement.

Prototype pollution

A JavaScript-specific class of vulnerability where merging untrusted JSON into an existing object can poison Object.prototype. Once polluted, every object in the program inherits the attacker's properties.

// VULNERABLE
function merge(target, source) {
  for (const key in source) {
    if (typeof source[key] === 'object') {
      merge(target[key] = target[key] || {}, source[key]);
    } else {
      target[key] = source[key];
    }
  }
}

merge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));
// Now ({}).isAdmin === true everywhere

The fix is to reject the keys __proto__, constructor, and prototype when merging untrusted input. Library-wise, recent versions of lodash.merge, jquery.extend, and most ecosystem utilities have hardened against this — keep dependencies updated. For your own merge utilities, Object.create(null) creates objects without a prototype chain, which is immune.

This is not theoretical. CVE-2018-16487 in lodash, multiple flaws in older jquery, and ongoing reports against npm packages mean this is an evergreen attack class.

JSONP and what replaced it

JSONP was a 2005-era workaround for the same-origin policy: wrap a JSON response in a <script> tag with a callback function. It worked, and it shipped arbitrary JavaScript into your page from the origin you queried. CSRF was trivial. Any compromised JSONP endpoint owned every page consuming it.

CORS replaced JSONP entirely around 2012. If you see a JSONP endpoint in 2026, either remove it or document it as legacy with a kill date. The amount of risk it carries is not justified by any modern use case.

Secrets in JWT and other payloads

Two repeated failures, both worth a careful read because they keep happening.

Secrets in JWT payloads. The JWT payload is base64-encoded JSON — not encrypted. Anyone with the token can read the contents using the JWT decoder. Putting a password, a private key, or PII in there is equivalent to publishing it. Use the payload only for identifiers and authorisation claims.

Algorithm confusion. The alg field in a JWT header tells the verifier which algorithm to use. Older libraries trusted this field — an attacker could send {"alg": "none"} and bypass signature checks entirely, or send {"alg": "HS256"} with a key the server thought was for RS256 (signing instead of verifying). Modern libraries (jose, recent jsonwebtoken) reject this. Pin the algorithm at the verify call: jwt.verify(token, key, {algorithms: ['RS256']}).

Validate before you trust

A JSON document that parses tells you nothing about its shape. {"role": "admin"} from an untrusted source is just a string — but if your authorisation code reads it without validation, the attacker is now admin.

The rule is to validate at the boundary, every time. JSON Schema or Zod, run synchronously before the data reaches any business logic. The schema validator on this site uses Ajv, the same engine you should compile into your production server.

// At every endpoint that takes JSON:
import Ajv from 'ajv';
const validate = ajv.compile(SCHEMA);

app.post('/api/users', (req, res) => {
  if (!validate(req.body)) {
    return res.status(400).json({ errors: validate.errors });
  }
  // From here, req.body is guaranteed to match the schema
});

Set additionalProperties: false on every object schema you control. Without it, extra keys are silently accepted — which means attackers can inject fields your code does not expect. With it, the validator rejects anything outside the contract.

Logging JSON safely

Two patterns that look harmless and are not.

Logging raw request bodies. If you write logger.info(JSON.stringify(req.body)) without redaction, you eventually log passwords, API keys, and credit card numbers — whatever a misbehaving client posted. Use a redacting logger (pino-noir, winston's formatter) and configure it to redact known-sensitive keys (password, token, authorization, credit_card).

Log injection via newlines. A string value like "normal text\n[ERROR] fake log line" renders as two log lines if your log format is line-delimited. Logs that an attacker can forge are useless for forensics. Either log as NDJSON (each entry one line, control characters escaped) or strip newlines from string fields before logging.

The checklist

One-screen summary for the team wiki:

  1. Cap JSON body size on every endpoint that takes JSON (limit: '100kb' is a sensible default).
  2. Validate every incoming JSON against a schema before it reaches business logic. Use additionalProperties: false.
  3. Escape <, >, &, and / when injecting server-rendered JSON into HTML. Or use <script type="application/json"> blocks.
  4. Block __proto__, constructor, prototype keys in any merge of untrusted JSON.
  5. Pin the JWT algorithm at the verify call. Never trust the alg field.
  6. Never put secrets in a JWT payload. It is base64, not encryption.
  7. Redact known-sensitive keys before logging JSON.
  8. Kill any remaining JSONP endpoints.

Most JSON-handling code I have audited gets four or five of these right. Getting all eight is the goal. None of them costs more than a few lines of code or a one-time library upgrade.

JSONCSVConvertersData