How to Check If String is a Json in PHP?

03-Apr-2023

.

Admin

How to Check If String is a Json in PHP?

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": "xyz@gmail.com"}';

$data2 = '{name:uday, email: xyz@gmail.com}';

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": "xyz@gmail.com"}';

$data2 = '{name:uday, email: xyz@gmail.com}';

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...

#PHP