W3docs

PHP json_decode() returns NULL with seemingly valid JSON?

There are a few possible reasons that json_decode() might return NULL when given what appears to be valid JSON.

There are a few possible reasons that json_decode() might return NULL when given what appears to be valid JSON. Here are a few things you might want to check:

  1. Make sure that the input string is actually a valid JSON string. You can use an online JSON linting tool to validate the syntax of your JSON string.
  2. Make sure that you are using the correct encoding when you read the JSON string from a file or receive it as a response from a network request. json_decode() expects UTF-8 encoded input, so if you are reading from a file that is encoded differently, or if you are receiving the JSON string from a network request that has a different encoding, json_decode() may not be able to parse it properly.
  3. Make sure that you are using the correct second argument for json_decode(). If you pass TRUE as the second argument, json_decode() will return an associative array instead of an object. If you pass FALSE, it will return an object. In PHP 7.3+, passing a non-boolean value (e.g. NULL) throws a TypeError instead of returning a value.
  4. Check for decode errors. If json_decode() returns NULL, use json_last_error() and json_last_error_msg() to identify the exact issue. For modern PHP (7.3+), consider using the JSON_THROW_ON_ERROR flag to automatically throw a JsonException on failure.
$json = '{"name": "John", "age": 30}';
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

if ($data === null) {
    echo 'Error: ' . json_last_error_msg();
}

I hope this helps! Let me know if you have any other questions.