Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

PHP’s json_decode() parses a JSON string; it does not find JSON embedded in surrounding prose. To handle mixed text, first isolate a candidate fragment using boundaries you know or a clearly defined scanning strategy, then pass that candidate to json_decode() and handle errors explicitly.

How to extract JSON from unstructured text in PHP

Separate extraction from parsing. Extraction decides which substring might be JSON; parsing checks whether that substring is valid JSON and turns it into a PHP value. The PHP manual documents decoding, not a general-purpose method for locating JSON inside arbitrary text.

When the surrounding format is known

Use the wrapper’s documented boundaries. For example, if an upstream format guarantees that JSON appears between specific markers, locate those markers and take the text between them. If the text uses code fences, remove the fences according to the format you accept. Then decode only the extracted candidate.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When the text is arbitrary

Define a candidate-scanning strategy, attempt to decode each candidate, and report when none succeeds. Do not assume a simple regular expression can reliably identify arbitrary nested JSON: braces and brackets can occur inside strings, and quotes can be escaped. The extraction algorithm is application-specific; it is not provided by json_decode().

Test the extractor against nested objects and arrays, braces or brackets inside quoted strings, escaped quotes, multiple JSON-like fragments, code fences, malformed JSON, valid null, and deeply nested values. These are practical cases your strategy should account for, not a guarantee that one generic scanning method will work for every input.

Decode an isolated candidate and catch failures

On PHP 7.3 and later, use JSON_THROW_ON_ERROR so a decoding failure raises JsonException instead of relying on a return value that can be ambiguous.

try {
    $value = json_decode($candidate, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    // Handle malformed JSON, invalid UTF-8, or excessive nesting.
}

Here, true asks for JSON objects to be returned as associative arrays. Pass false or omit that argument if your code expects objects instead. Choose a depth limit that fits the data your application accepts; the example uses the decoder’s commonly used depth value, but a stricter limit may be appropriate for your input.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The decoder’s depth parameter bounds nesting. Invalid JSON, invalid UTF-8, or input exceeding the configured depth can fail, so handle exceptions at the boundary where your application can log, reject, or otherwise recover from the input.

Why can json_decode() return null?

JSON null is valid JSON and decodes to PHP null. Without JSON_THROW_ON_ERROR, a failed decode can also return null. Andrea Faulds’s PHP RFC “JSON_THROW_ON_ERROR,” dated 2017-09-10, describes the ambiguity: “json_decode() returns null upon erroring, but null is also a possible valid result (if decoding the JSON “null”).”

On PHP 7.3 and later, the exception flag distinguishes failure from a valid decoded null. For older runtimes, inspect the error state immediately after decoding:

$value = json_decode($candidate, true, 512);

if (json_last_error() !== JSON_ERROR_NONE) {
    $message = json_last_error_msg();
    // Handle the decoding error.
}

Do not treat $value === null by itself as proof of failure. See the PHP manual’s error inspection functions for the available error reporting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose decoding, validation, and result shape

Need Use What it does
Use the parsed data json_decode() Returns a PHP value; choose object or associative-array output through the associative argument. PHP manual.
Check syntax only; decoded value is not needed json_validate(), PHP 8.3 and later Returns whether the input is syntactically valid JSON. PHP manual.
Support a runtime without JSON_THROW_ON_ERROR json_decode() followed immediately by json_last_error() Checks the legacy error state; available for older compatibility requirements. PHP manual.

If you need the decoded value, decode once rather than calling json_validate() and then decoding the same string. The PHP manual positions validation for cases where the decoded value is not immediately needed.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle UTF-8 and malformed input deliberately

json_decode() expects UTF-8 input. By default, treat invalid input as a data-quality problem and handle the failure rather than silently changing bytes. The JSON_INVALID_UTF8_IGNORE and JSON_INVALID_UTF8_SUBSTITUTE flags, available from PHP 7.2.0, change that behavior: ignore drops invalid bytes, while substitute replaces them with U+FFFD. Use either only if that transformation is acceptable for your application. The PHP JSON constants manual documents these flags.

For emitted JSON, json_encode() has its own failure handling and also requires UTF-8 string data. Where supported, JSON_THROW_ON_ERROR can make encoding errors explicit as well. Encoding is a separate operation from extracting and decoding input; consult the PHP manual for json_encode().

Check PHP compatibility before using these flags

  • JSON_INVALID_UTF8_IGNORE and JSON_INVALID_UTF8_SUBSTITUTE are available from PHP 7.2.0.
  • JSON_THROW_ON_ERROR and JsonException support are available from PHP 7.3.0.
  • json_validate() was introduced in PHP 8.3.

Verify the PHP version used by the deployed application, not just the version on a development machine. The json_decode() reference and JSON constants reference list decoder options and their version notes. The constants documentation also notes that JSON_PARTIAL_OUTPUT_ON_ERROR takes precedence over JSON_THROW_ON_ERROR; this chiefly matters when encoding requests partial output.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.