php
data_processing
ai_generated
true
json_decode(): Maximum stack depth exceeded
ID: php/json-max-depth
88%Fix Rate
90%Confidence
45Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 83 | active | — | — | — |
Root Cause
JSON max depth errors occur when json_decode() encounters a JSON structure nested deeper than the default 512 levels. This can indicate deeply nested API responses, recursive data structures, or malicious payloads designed to cause resource exhaustion.
genericWorkarounds
-
90% success Increase the depth parameter to a reasonable value based on expected data structure
Pass a larger depth as the third argument: json_decode($json, true, 1024). Choose a value based on the known maximum nesting of your data. Values between 512 and 2048 are safe for most use cases.
-
85% success Validate and limit nesting depth before processing untrusted JSON
For untrusted input, use a streaming JSON parser (e.g., JsonMachine) that processes tokens incrementally without building the full structure in memory. Alternatively, validate depth with a simple counter before calling json_decode().
Dead Ends
Common approaches that don't work:
-
Setting the depth parameter to PHP_INT_MAX
72% fail
Extremely deep recursion in JSON parsing can exhaust the C-level stack, causing a segfault rather than a PHP error. It also opens the application to denial-of-service attacks via crafted deeply nested JSON payloads.
-
Pre-processing the JSON string with regex to flatten it before decoding
80% fail
Regex-based JSON manipulation is inherently fragile and will break on escaped characters, unicode sequences, and edge cases. It also adds significant processing overhead for large payloads.
Error Chain
Leads to:
Preceded by:
Frequently confused with: