How to validate JSON in PHP
Snippet
The function json_last_error returns the last error occurred during the JSON encoding and decoding.
<?php
function isJSON($string) {
if(is_array($string)) return false;
if(!empty($string)){
if($string == '{}') return true;
json_decode($string);
if(json_last_error() === JSON_ERROR_NONE) return true;
}
return false;
}
$json = '{"website":{"domain":"wtools.io","title":"Online Web Tools"}}';
if(isJSON($json)){
echo "Valid JSON string";
} else {
echo "Not valid JSON string";
}
But a better way is a function that returns an array or false if JSON is not valid (To avoid call the json_decode function 2 times):
<?php
function isJSON($string) {
if(!empty($string) && !is_array($string)){
if($string == '{}') return [];
$res = json_decode($string, true);
if(json_last_error() === JSON_ERROR_NONE) return $res;
}
return false;
}
$json = '{"website":{"domain":"wtools.io","title":"Online Web Tools"}}';
$data = isJSON($json);
if($data!==false){
print_r($data);
} else {
echo "Not valid JSON string";
}
If you want to validate JSON online, then you can use our free tool.
Similar Snippets
- Check if string starts with certain characters
- Validate Email
- Case-Insensitive in_array
- Check if all values in array are equal
- Check if array is associative
- How to check the connection to MySQL
- Validate XML
- Check if two arrays values are equal
- Check if bit flag is set
- Check if a string is serialized