Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

Decode JSON Embedded in Text Without Hiding PHP Parse Errors

PHP’s json_decode() parses a JSON string, not JSON hidden in prose. Isolate a candidate first, then decode it with deliberate error, encoding, and depth handling.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

json_decode() parses a JSON string; it does not search prose for JSON. To handle JSON surrounded by other text, first isolate a candidate fragment, then pass that fragment to PHP’s decoder and handle parse errors explicitly. PHP 7.3 and later can use JSON_THROW_ON_ERROR with try/catch.

Why can’t json_decode() extract JSON from prose?

json_decode() accepts a JSON-encoded string and converts it into a PHP value. It does not define a general way to find where a JSON object or array begins and ends inside arbitrary text. The PHP manual documents decoding, not boundary detection. PHP Manual: json_decode

As an Amazon Associate I earn from qualifying purchases.

For a known wrapper, remove the wrapper using its documented boundaries. For example, if an API response always places a JSON payload between fixed markers, locate those markers and extract the text between them before decoding. If the surrounding text has no reliable structure, you need a candidate-scanning strategy: identify plausible spans, try to parse them, and report when none succeeds.

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

Do not treat a regular expression that stops at the next closing brace as a general solution. Nested objects, braces inside quoted strings, escaped quotes, multiple fragments, and malformed input can all make a simple boundary guess wrong. PHP’s decoder can tell you whether a candidate is valid JSON; it cannot tell you that your extraction heuristic found the intended candidate.

How to decode an isolated candidate safely

Once $candidate contains only the fragment you intend to parse, use json_decode() with an explicit depth limit and, on PHP 7.3 or later, JSON_THROW_ON_ERROR:

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

With the second argument set to true, JSON objects decode as associative arrays. Use false (the default) if your code expects objects instead. Choose deliberately: the result shape affects how callers access fields and distinguish objects from arrays. The decoder’s depth argument limits nesting; excessively deep or invalid input can fail. PHP Manual: json_decode

JSON_THROW_ON_ERROR was added in PHP 7.3. It makes decoding failures throw JsonException, so the exception handler is the explicit error path. PHP Manual: JSON constants

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

What should you test in an extraction strategy?

There is no universal boundary detector established by PHP’s decoder. Test your own candidate-selection logic against the kinds of text it will actually receive, including:

  • Nested objects and arrays.
  • Braces or brackets inside quoted strings, plus escaped quotes.
  • Several JSON-like fragments in one message.
  • Surrounding code fences or other known wrappers.
  • Malformed JSON, valid JSON null, and deeply nested values.

Define what happens when multiple candidates parse successfully: for example, select according to a documented wrapper or reject ambiguous input. If no candidate parses, return or log a clear failure rather than silently treating arbitrary text as JSON.

Why does json_decode() return null?

null can be the correct result: the JSON text null decodes to PHP null. Without exceptions, the same return value can also indicate a decoding error, so checking only whether the result is null is ambiguous. Andrea Faulds noted this issue in the PHP RFC “JSON_THROW_ON_ERROR,” dated September 10, 2017. PHP RFC: JSON_THROW_ON_ERROR

On PHP 7.3 or later, prefer the exception approach shown above. If you must support older PHP versions, inspect the decoder’s error state immediately after each decode:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$value = json_decode($candidate, true, 512);

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

Check the error before another JSON operation changes the relevant state. PHP Manual: json_last_error

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

How should you handle malformed JSON and invalid UTF-8?

PHP’s JSON decoder expects UTF-8 input. Decide whether invalid bytes should make the input fail or whether your application explicitly accepts changing the data. The flags JSON_INVALID_UTF8_IGNORE and JSON_INVALID_UTF8_SUBSTITUTE are available from PHP 7.2: the first drops invalid bytes, while the second replaces them with U+FFFD. These options alter input rather than merely reporting an error, so use them only when that transformation is acceptable for your data. PHP Manual: json_decode PHP Manual: JSON constants

For data that must remain intact, rejecting invalid input and handling the resulting error is generally safer than silently repairing it. Also keep an intentional depth limit: a candidate can be syntactically invalid or too deeply nested to decode at the limit you set.

Should you validate JSON or decode it?

Use json_decode() when your code needs the PHP value. PHP 8.3 introduced json_validate(), which returns a boolean indicating whether a string is syntactically valid JSON. The manual recommends it for cases where you do not need the decoded value immediately. Validating and then decoding the same candidate performs an unnecessary second pass when the value is needed; decode once and handle the result or exception instead. PHP Manual: json_validate

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

Which approach fits your PHP version?

Need Approach Availability or consideration
Decode a candidate and handle failure locally json_decode() with JSON_THROW_ON_ERROR and try/catch PHP 7.3 and later. PHP Manual: JSON constants
Support older runtimes without the exception flag Decode, then check json_last_error() and, if needed, json_last_error_msg() Check the error state immediately after decoding. PHP Manual: json_last_error
Check syntax only; do not need the decoded value json_validate() Introduced in PHP 8.3. If you need the value, decode rather than validating and then decoding. PHP Manual: json_validate
Choose the PHP representation of JSON objects Set the associative argument of json_decode() to true for associative arrays or false for objects Choose based on the types the rest of your code expects. PHP Manual: json_decode
Decide how to treat invalid UTF-8 Reject it, or deliberately use an ignore or substitute flag The flags can discard or replace data; both are available from PHP 7.2. PHP Manual: JSON constants

Check the PHP runtime used by the application before relying on version-specific flags or functions. If your workflow later re-encodes decoded values, remember that json_encode() also requires UTF-8 string data and has its own error handling; JSON_THROW_ON_ERROR is supported there as well. PHP Manual: json_encode

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.