JSON Security: Protecting Your Applications

jsonsecuritybest-practices

While JSON itself is safe, improper handling can introduce security vulnerabilities. Here's what to watch for and how to stay safe.

JSON Injection

Never construct JSON by string concatenation with user input. Always use proper serialization:

// ❌ Dangerous

const json = '{"name":"' + userInput + '"}';

// ✅ Safe

const json = JSON.stringify({ name: userInput });

JSON Hijacking

Older browsers were vulnerable to JSON hijacking through array literals. Modern browsers have fixed this, but always return objects (not arrays) at the top level of API responses.

Denial of Service via Large Payloads

Malicious users can send extremely large JSON to exhaust memory:

  • Set maximum request body sizes
  • Use streaming parsers for large JSON
  • Validate structure before processing
  • Prototype Pollution

    Parsing untrusted JSON with eval() can lead to prototype pollution. Always use JSON.parse():

    // ❌ Never do this

    const obj = eval('(' + jsonString + ')');

    // ✅ Always use JSON.parse

    const obj = JSON.parse(jsonString);

    Content-Type Headers

    Always set the correct Content-Type header:

    Content-Type: application/json

    This prevents browsers from interpreting JSON responses as HTML or scripts.

    Use our JSON Viewer to safely inspect JSON data in your browser.

    Related Tools