Skip to content

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.

Here are the error codes you’ll run into most often:

ConstantMeaning
JSON_ERROR_NONENo error occurred
JSON_ERROR_DEPTHMaximum stack depth exceeded
JSON_ERROR_STATE_MISMATCHUnderflow or modes mismatch
JSON_ERROR_CTRL_CHARUnexpected control character found
JSON_ERROR_SYNTAXSyntax error, malformed JSON
JSON_ERROR_UTF8Malformed UTF-8 characters
JSON_ERROR_UNSUPPORTED_TYPEA value of a type that cannot be encoded was given
JSON_ERROR_INVALID_PROPERTY_NAMEA property name that cannot be encoded was given

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";
}

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
}

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";
}

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
}