Validating JSON Data in PHP
When you call json_decode() or json_encode() in PHP, things can go wrong. The JSON might have a typo, a missing bracket, or contain data that PHP can’t convert. The problem is that these functions don’t throw exceptions by default. Instead, they fail silently and return null or false.
That’s where json_last_error() comes in. After any JSON operation, you can call it to check whether something went wrong and get a specific error code telling you what failed.
Error Codes
Section titled “Error Codes”Here are the error codes you’ll run into most often:
| Constant | Meaning |
|---|---|
JSON_ERROR_NONE | No error occurred |
JSON_ERROR_DEPTH | Maximum stack depth exceeded |
JSON_ERROR_STATE_MISMATCH | Underflow or modes mismatch |
JSON_ERROR_CTRL_CHAR | Unexpected control character found |
JSON_ERROR_SYNTAX | Syntax error, malformed JSON |
JSON_ERROR_UTF8 | Malformed UTF-8 characters |
JSON_ERROR_UNSUPPORTED_TYPE | A value of a type that cannot be encoded was given |
JSON_ERROR_INVALID_PROPERTY_NAME | A property name that cannot be encoded was given |
Examples
Section titled “Examples”1. Decoding valid JSON
Section titled “1. Decoding valid JSON”After calling json_decode(), check json_last_error() to make sure the data was parsed correctly:
$json_data = '{"name": "John", "age": 30}'; // Valid JSON
$data = json_decode($json_data);
if (json_last_error() === JSON_ERROR_NONE) { echo "JSON decoded successfully.\n"; print_r($data);} else { echo "Error decoding JSON: " . json_last_error_msg() . "\n";}2. Handling malformed JSON
Section titled “2. Handling malformed JSON”If the JSON string has a syntax problem (like a missing bracket), json_decode() returns null. You catch it like this:
$malformed_json = '{"name": "John", "age": 30'; // Missing closing bracket
$data = json_decode($malformed_json);
if (json_last_error() !== JSON_ERROR_NONE) { echo "Error decoding JSON: " . json_last_error_msg() . "\n"; // Output: Error decoding JSON: Syntax error}3. Encoding data to JSON
Section titled “3. Encoding data to JSON”The same pattern works for json_encode(). Check for errors right after the call:
$data_array = ['name' => 'John', 'age' => 30];
$json_data = json_encode($data_array);
if (json_last_error() === JSON_ERROR_NONE) { echo "JSON encoded successfully.\n"; echo $json_data;} else { echo "Error encoding JSON: " . json_last_error_msg() . "\n";}4. Encoding unsupported types
Section titled “4. Encoding unsupported types”Some PHP values can’t be converted to JSON. For example, file resource handles will cause json_encode() to fail:
// Using a resource in data (which cannot be encoded)$data_with_resource = ['name' => 'John', 'file' => fopen('example.txt', 'r')];
$json_data = json_encode($data_with_resource);
if (json_last_error() !== JSON_ERROR_NONE) { echo "Error encoding JSON: " . json_last_error_msg() . "\n"; // Output: Error encoding JSON: Object of class resource could not be converted to string}