ENRU

JSON nesting too deep: what “Maximum stack depth exceeded” means and how to fix it

Updated

Five hundred and twelve levels of brackets is a lot. Past that it’s usually a generator bug, not data. Every parser has a depth limit, written down or not, and a document deeper than that fails however valid it is.

What too deep looks like, and the flat version

Hand-written JSON rarely goes past ten levels. Documents that hit a limit grow by themselves: a reply inside a reply inside a reply, a tree serialized with a cycle in it, an envelope wrapped around the payload on every retry. This shape adds a level per record:

{"id": 1, "reply": {"id": 2, "reply": {"id": 3, "reply": {"id": 4, "reply": null}}}}

A thousand replies make a thousand levels. The same data as a flat list with parent ids stays two levels deep however long the thread gets:

[{"id": 1, "parent": null}, {"id": 2, "parent": 1}, {"id": 3, "parent": 2}, {"id": 4, "parent": 3}]

Why JSON parsers limit nesting (RFC 8259)

The grammar has no limit: [[[[1]]]] is valid at any depth. RFC 8259, section 9 leaves it to the parser: “An implementation may set limits on the maximum depth of nesting.” So every parser picks its own, and the numbers below differ by a factor of a hundred.

The reason for a limit is the call stack. Many parsers handle an array by calling themselves for each element, so each level costs a stack frame; a megabyte of [ is a million levels. Without a limit that is a crash, and an easy denial of service for any endpoint that parses what it’s sent.

JSON depth limits by parser

Measured on 2026-11-08 by parsing nested arrays of increasing depth, [[…]]. “Levels” counts brackets: [[1]] is two.

ParserDefault limitMessage past the limit
Chrome 156, Node 24–25 (V8)None hit: 1,000,000 levels parsedNo error
Safari 27 (JavaScriptCore)None hit: 100,000 levels parsedNo error
Python 3.9994 levels (recursion limit 1000)RecursionError: maximum recursion depth exceeded while decoding a JSON array from a unicode string
Python 3.14Set by the C stack: 6,334 levels on Alpine LinuxRecursionError: Stack overflow (used 992 kB) while decoding a JSON array from a unicode string
Go 1.25–1.2610,000invalid character '[' exceeded max depth
Go 1.2710,000exceeded max depth
Java, Jackson 2.151,000Depth (1001) exceeds the maximum allowed nesting depth (1000)
Java, Jackson 2.231,000Below the table
C#, System.Text.Json 1064The maximum configured depth of 64 has been exceeded. Cannot read next JSON array.
C#, Newtonsoft.Json 1364Starts with “The reader” and names MaxDepth of 64
PHP 8.3depth 512, which lets through 511 nested arraysMaximum stack depth exceeded (error code 1)
Rust, serde_json 1.0128 nested arrays already failrecursion limit exceeded at line 1 column 128
jq 1.7.1256Exceeds depth limit for parsing at line 1, column 257
MySQL 8.4100The JSON document exceeds the maximum depth.
JSON Statham512Nesting too deep, at the 513th opening bracket
Document nesting depth (1001) exceeds the maximum allowed (1000, from `StreamReadConstraints.getMaxNestingDepth()`)

The spread is the real problem. A document of 100 levels passes Go, Jackson, PHP and Python and fails in C# with its default 64; MySQL refuses 101. A service that accepts what it can parse may produce what its neighbour can’t.

How to measure depth and set the limit

First find out how deep the document is. The JavaScript and Python functions below count brackets outside strings and work even on text the parser refuses; Go counts tokens with json.Decoder. Then raise the limit only if the depth is real and the input is trusted. All snippets were run on 512 and 513 levels.

JavaScript: depth of a JSON text

function maxDepth(text) {
  let depth = 0;
  let deepest = 0;
  let inString = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (inString) {
      if (c === '\\') i++;
      else if (c === '"') inString = false;
    } else if (c === '"') inString = true;
    else if (c === '{' || c === '[') deepest = Math.max(deepest, ++depth);
    else if (c === '}' || c === ']') depth--;
  }
  return deepest;
}

Python

def max_depth(text):
    depth = deepest = 0
    in_string = escaped = False
    for c in text:
        if in_string:
            if escaped:
                escaped = False
            elif c == "\\":
                escaped = True
            elif c == '"':
                in_string = False
        elif c == '"':
            in_string = True
        elif c in "[{":
            depth += 1
            deepest = max(deepest, depth)
        elif c in "]}":
            depth -= 1
    return deepest

Python has no depth option. On 3.9 a higher sys.setrecursionlimit lets json.loads go deeper; on 3.14 the C stack is the limit and the setting doesn’t help past it. Flattening the data is the fix that works everywhere.

Go

import (
	"encoding/json"
	"errors"
	"io"
	"strings"
)

func maxDepth(input string) (int, error) {
	dec := json.NewDecoder(strings.NewReader(input))
	depth, deepest := 0, 0
	for {
		tok, err := dec.Token()
		if errors.Is(err, io.EOF) {
			return deepest, nil
		}
		if err != nil {
			return deepest, err
		}
		switch tok {
		case json.Delim('{'), json.Delim('['):
			depth++
			deepest = max(deepest, depth)
		case json.Delim('}'), json.Delim(']'):
			depth--
		}
	}
}

The limit of 10,000 in encoding/json is fixed; Go 1.27 applies it to Decoder.Token too, so this function reports 10,000 and the error for anything deeper.

Java (Jackson): set the limit explicitly

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.StreamReadConstraints;
import com.fasterxml.jackson.databind.ObjectMapper;

static ObjectMapper mapperWithDepth(int maxDepth) {
    JsonFactory factory = JsonFactory.builder()
        .streamReadConstraints(StreamReadConstraints.builder().maxNestingDepth(maxDepth).build())
        .build();
    return new ObjectMapper(factory);
}

C# (System.Text.Json)

using System.Text.Json;

static JsonDocument ParseDeep(string text) =>
    JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 512 });

The same MaxDepth exists on JsonSerializerOptions and JsonReaderOptions; the default, 0, means 64 (MaxDepth docs).

PHP

$data = json_decode($text, true, 513, JSON_THROW_ON_ERROR);

PHP counts one level more than there are brackets: depth 512 rejects 512 nested arrays, so 513 is what accepts them.

How to keep JSON shallow

  • Store trees flat. A list of nodes with parent ids, or a path per node, keeps depth constant however big the tree grows.
  • Look for cycles. Serializers refuse a direct cycle (Converting circular structure to JSON, ValueError: Circular reference detected, json: unsupported value: encountered a cycle), but hand-rolled ones and copies with a depth cap produce a document exactly as deep as their limit.
  • Wrap once. Middleware that adds an envelope on every retry or hop turns a flat payload into a deep one; unwrap before you wrap again.
  • Agree on a limit along the pipeline. The strictest reader decides: if one consumer uses C# defaults, 64 is your real limit.

Check nesting depth in the validator

Try it: open the too-deep sample in the Validator. JSON Statham accepts 512 levels of objects and arrays, counted together, and reports the 513th opening bracket with its line and column. For valid documents the validator shows the depth in its statistics, so you can see how close you are before a parser complains.

JSON nesting depth FAQ

What is the maximum nesting depth of JSON?

The standard sets none; RFC 8259 lets each parser choose. Defaults: 64 in C#, 100 in MySQL, 256 in jq 1.7, 512 in PHP and JSON Statham, 1,000 in Jackson, 10,000 in Go; V8 has no fixed limit.

How do I raise the depth limit?

C#: MaxDepth in the options. Jackson: StreamReadConstraints with maxNestingDepth. PHP: the third argument of json_decode. Go’s 10,000 is fixed, Python’s follows the stack. Raise it only for trusted input.

What does “Maximum stack depth exceeded” mean in PHP?

json_decode went past its depth argument, 512 by default. PHP counts one level more than there are brackets, so 512 nested arrays need depth 513. The error code is 1.

How deep can JSON be in JSON Statham?

512 levels of objects and arrays together. The 513th opening bracket gets “Nesting too deep” with its line and column.