How to Check If String is a Json in PHP?
Teams applying “How to Check If String is a Json in PHP?” in a production project can use the official resource to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the PHP project and test it against the project’s actual database and runtime.
Hi Dev,
Here, I will show you how to works How to check if string is a json in PHP. you can see Validate json in PHP example. we will help you to give example of Check if string is a json or not. you can understand a concept of Json functions and operators in PHP.
json_decode($data, true) will return an object converted into an associative array, and then the is_array() function checks whether the object is an array or not. The json_last_error() returns the last error if there were any errors when json_decode() was invoked.
Example 1:
index.php
<?php
function json_validator($data) {
if (!empty($data)) {
return is_string($data) &&
is_array(json_decode($data, true)) ? true : false;
}
return false;
}
$data1 = '{"name":"uday", "email": "[email protected]"}';
$data2 = '{name:uday, email: [email protected]}';
echo "Result for data1: ";
echo (json_validator($data1) ? "JSON is Valid\n"
: "JSON is Not Valid\n");
echo "Result for data2: ";
echo (json_validator($data2) ? "JSON is Valid"
: "JSON is Not Valid");
?>
Output:
Result for data1: JSON is Valid
Result for data2: JSON is Not Valid
Example 2:
index.php
<?php
function json_validator($data) {
if (!empty($data)) {
@json_decode($data);
return (json_last_error() === JSON_ERROR_NONE);
}
return false;
}
$data1 = '{"name":"uday", "email": "[email protected]"}';
$data2 = '{name:uday, email: [email protected]}';
echo "Result for data1: ";
echo (json_validator($data1) ? "JSON is Valid\n"
: "JSON is Not Valid\n");
echo "Result for data2: ";
echo (json_validator($data2) ? "JSON is Valid"
: "JSON is Not Valid");
?>
Output:
Result for data1: JSON is Valid
Result for data2: JSON is Not Valid
I hope it could help you...
- How To Use Php Conditional Statement Example
- How to Check if String Contains Regex in PHP?
- PHP Array_column() Function Example
- PHP Generate List of Random Numbers Between 0 and 100 Example
- How to User Login with Facebook in PHP?
- How to Explode Every Character into Array Using PHP Example?
- PHP Form Validation Tutorial
- PHP Convert XML to JSON Example