JSON Code Snippets: Safe Parsing, Deep Merging, and Validating Untrusted Payloads

Rows of labeled card catalog drawers in a library

JSON feels like the safest part of any integration. It is plain text, every language reads it, and a parse call is one line. That reputation is exactly why so many production bugs start there: a webhook delivers a field as a string instead of a number, a config file arrives with a trailing comma, a merge helper copies a key it should have refused. None of these are exotic. They are what happens when a payload is trusted a few lines before it has been checked.

This collection is a set of small, copy-friendly snippets in JavaScript and Python for the moments where JSON causes trouble: parsing without crashing the request, merging objects without letting a hostile key rewrite your prototype, validating shape before the data reaches business logic, and serializing in a way that does not produce surprise diffs. Each section explains what the snippet protects against, so you can adapt it instead of pasting blindly.

Rows of labeled card catalog drawers in a library
Photo by jesse orrico on Unsplash

Parse defensively and keep the failure small

The built-in parsers throw on malformed input, which is correct behavior. The mistake is letting that exception escape from the middle of a request handler and take the whole call down with a stack trace. Wrap the parse, return a result you can branch on, and keep the error message short enough to log without leaking the payload.

function safeParse(text) {
  try {
    return { ok: true, value: JSON.parse(text) };
  } catch (err) {
    return { ok: false, error: err.message.slice(0, 120) };
  }
}

The same pattern in Python is nearly identical. The json module in the Python standard library documentation raises JSONDecodeError, which carries a line and column that are genuinely useful for debugging a bad upload.

import json

def safe_parse(text):
    try:
        return True, json.loads(text)
    except json.JSONDecodeError as err:
        return False, f"line {err.lineno}, col {err.colno}: {err.msg}"

Notice what the helper does not do: it does not try to repair the input. Auto-fixing trailing commas or single quotes feels friendly, but it hides a producer bug that will come back next week in a different shape. Fail clearly and tell the sender what was wrong.

Know what the parser will and will not preserve

JSON has fewer types than most languages, and the gaps cause quiet corruption. There is no date type, so dates travel as strings and need an agreed format. There is no integer versus float distinction at the format level, and the JSON specification in RFC 8259 explicitly leaves number precision to the implementation. In JavaScript every number becomes a double, which means integers beyond 9007199254740991 lose precision silently.

If a payload carries identifiers that large, such as a 64-bit database key, treat them as strings at the producer and keep them as strings in your code. A parsed identifier that ends in the wrong digits will not throw an error. It will simply look up a different record, or none at all.

const MAX_SAFE = Number.MAX_SAFE_INTEGER;

function assertSafeNumbers(obj, path = "") {
  for (const [key, val] of Object.entries(obj)) {
    const here = path ? `${path}.${key}` : key;
    if (typeof val === "number" && Math.abs(val) > MAX_SAFE) {
      throw new RangeError(`unsafe number at ${here}`);
    }
    if (val && typeof val === "object") assertSafeNumbers(val, here);
  }
}

This guard runs after the parse, so it cannot recover digits that were already lost, but it does tell you when a payload has crossed the line. For true protection, agree with the sender that large identifiers are strings.

Merge objects without inviting prototype pollution

Deep merge helpers are a classic place for a security bug. A naive recursive merge that copies every key from a source object will happily follow a key named __proto__ or constructor, and write onto a prototype shared by every object in the process. The OWASP project documents this class of problem under its injection and input validation guidance, and it has produced real vulnerabilities in widely used libraries.

The fix is small. Refuse the dangerous keys, and only merge plain objects.

const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);

function isPlain(v) {
  return v !== null && typeof v === "object" && !Array.isArray(v);
}

function deepMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (BLOCKED.has(key)) continue;
    if (isPlain(source[key]) && isPlain(target[key])) {
      deepMerge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

Two judgment calls are baked in. Arrays are replaced rather than concatenated, because merging arrays by index produces results nobody expects. And null in the source overwrites the target, which is usually what a config override means. If your use case differs, change those two lines on purpose rather than discovering the behavior in production.

Whiteboard with branching diagram arrows
Photo by Thirdman on Pexels

Validate shape before the data touches business logic

Parsing tells you the text was valid JSON. It says nothing about whether the result has the fields you need, in the types you need. The cheapest place to catch a mismatch is a single validation step at the boundary, so the rest of the code can assume a clean shape.

JSON Schema is a portable way to describe that shape, and it has validators in nearly every language, which matters when the producer and consumer are written by different teams. For TypeScript codebases, a library such as Zod keeps the schema and the static type in one place.

import { z } from "zod";

const Order = z.object({
  id: z.string().min(1),
  quantity: z.number().int().positive(),
  shipTo: z.object({ postalCode: z.string().regex(/^\d{5}$/) }),
  note: z.string().max(500).optional(),
});

const result = Order.safeParse(payload);
if (!result.success) {
  return { status: 422, issues: result.error.issues };
}

Return a specific status and the list of issues, not a generic failure. Whoever is integrating against you will fix a precise message in minutes and a vague one in days.

Handle missing, null, and unknown fields on purpose

Three situations look similar and mean different things: the key is absent, the key is present with a null value, and the key is present with a value you did not expect. Treating all three as "falsy" is how a customer's explicit request to clear a field gets ignored, or how a typo in a field name silently does nothing.

MISSING = object()

def read_field(data, key):
    value = data.get(key, MISSING)
    if value is MISSING:
        return "absent"       # leave stored value alone
    if value is None:
        return "clear"        # caller asked to erase it
    return "set"              # use the provided value

Unknown keys deserve a decision too. A strict API rejects them, which catches typos early but breaks when a producer adds a field. A tolerant one ignores them, which survives change but hides mistakes. Pick one per endpoint, document it, and apply it consistently.

Serialize in a stable, diff-friendly way

When JSON is written to a file, a cache, or a log, key order and whitespace become part of the contract. Two logically identical objects that serialize differently will fail a hash comparison, produce noisy version control diffs, and defeat cache keys.

import json

def stable_dumps(obj):
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)

Sorted keys and compact separators give you a deterministic string you can hash or compare. For files people read, use indent=2 with sort_keys=True instead. The MDN reference for JSON.stringify covers the replacer argument, which is the JavaScript route to the same result, along with the quirks that bite: undefined values and functions are dropped from objects, and circular references throw.

"Most data bugs we get called in to fix are not clever. A field changed type, a null showed up where it never had before, and nothing at the boundary was checking. A twenty-line validation step would have caught every one of them." - Dennis Traina, founder of 137Foundry

Network cables neatly labeled in a rack
Photo by Jandira Sonnendeck on Unsplash

Stream and bound large payloads

Parsing a large document in one call loads the full text and the full object tree into memory at the same time, so peak usage can be several times the file size. For an upload endpoint that accepts arbitrary customer data, that is a denial of service waiting for a motivated sender.

Bound the input before you parse it. Reject bodies over a fixed size at the edge, and for batch imports prefer newline-delimited JSON, where each line is its own document you can parse, validate, and discard one at a time.

import json

def read_ndjson(path, max_line=1_000_000):
    with open(path, "r", encoding="utf-8") as handle:
        for number, line in enumerate(handle, start=1):
            if len(line) > max_line:
                raise ValueError(f"line {number} exceeds size limit")
            if line.strip():
                yield json.loads(line)

A failure on line 40,211 now tells you exactly where to look, and the 40,210 good records before it were already processed. That behavior is far kinder than a single parse error on a four hundred megabyte file with no location attached.

Lab notebook and instruments on a desk
Photo by contact me +923323219715 on Pexels

Test the awkward inputs before they find you

A parser wrapper is only as trustworthy as the inputs it has been tried against. Keep a small fixture list of the payloads that cause trouble in the real world and run every new helper against it. The list does not need to be long, but it should be nasty.

Include an empty string, a bare null, a top-level array where you expect an object, a number just past the safe integer limit, a string with an embedded null character, deeply nested arrays, duplicate keys, and a field whose value is the wrong type. Duplicate keys are worth a special mention: the format does not forbid them, and different parsers keep the first or the last, so two services reading the same payload can disagree about what it said.

When these fixtures live next to the code and run in your normal test suite, the next person who touches the helper finds out in seconds whether they changed its behavior. That is the cheapest insurance available for code that sits on the front door of your system.

When the snippets stop being enough

Small helpers cover the boundary of a single service well. They start to strain when many systems exchange JSON that evolves independently: versions drift, fields get renamed, and a producer deploys on a Friday without telling anyone. At that point the problem is no longer a parsing snippet, it is an agreement between teams and a way to detect when the agreement breaks.

If your integrations have reached that stage, 137Foundry's data integration service works on exactly this kind of problem, from schema contracts to monitoring for payloads that drift. And if the JSON handling sits inside a larger application that needs a careful review, the team also does web development work on the surrounding code.

Whatever route you take, the principle from the snippets above holds: parse small, validate early, merge deliberately, and write output you can compare. JSON is easy to read and easy to trust, and the habit that keeps it safe is refusing to trust it until it has proven itself.

Need help with Web Development?

137Foundry builds custom software, AI integrations, and automation systems for businesses that need real solutions.

Book a Free Consultation View Services