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:
- 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.
- 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.
- Make sure that you are using the correct second argument for json_decode(). If you pass
TRUEas the second argument, json_decode() will return an associative array instead of an object. If you passFALSE, it will return an object. In PHP 7.3+, passing a non-boolean value (e.g.NULL) throws aTypeErrorinstead of returning a value. - Check for decode errors. If json_decode() returns
NULL, usejson_last_error()andjson_last_error_msg()to identify the exact issue. For modern PHP (7.3+), consider using theJSON_THROW_ON_ERRORflag to automatically throw aJsonExceptionon 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.