[PHP] Check for errors after encoding or decoding JSON

Created on November 30, 2026

json_last_error() returns the error code from the last JSON operation that ran without JSON_THROW_ON_ERROR. Check it after json_encode() or json_decode(). JSON_ERROR_NONE indicates success.

<?php

// The closing quote of the JSON string is missing.
$raw_json = '{"name":"Taro}';
$user = json_decode($raw_json);

if (json_last_error() !== JSON_ERROR_NONE) {
  echo 'Failed to decode json.';
}
Failed to decode json.

Reference

PHP