I found that many of you use a function like this...
function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
(from Fastest way to check if a string is JSON in PHP?)
Many of json encoded string contain these characters { : , "
If i check the string that contain these characters it may return true.
example:
$var = '{"1":"a2","a2":{"1":"a2.2","2":"a2.2"}}';
var_dump(isJson($var)) // true;
But when i check the string that is just a number, it return true too.
example:
$phone = '021234567';
var_dump(isJson($phone)); // true
I don't think the string '021234567' is json encoded and it should return false.
Let see more example for more clear question.
$var1 = '021234567'; // this is string. not integer. NOT json encoded.
$var2 = '"021234567"'; // this is json encoded.
$var3 = 021234567; // this is integer. NOT json encoded.
$var4 = 'bla bla'; // this is string. NOT json encoded.
$var5 = '{"1":"a2","a2":{"1":"a2.2","2":"a2.2"}}'; // this is json encoded.
var_dump(isJson($var1));
var_dump(isJson($var2));
var_dump(isJson($var3));
var_dump(isJson($var4));
var_dump(isJson($var5));
the results are:
true
true
true
false
true
But the expected results are:
false
true
false
false
true
The question is. How to check the string that is valid json encoded?
More example 2
If 021234567 is an integer. when i use json_encode it returns integer and have nothing to do with it again when use json_decode
$var = 021234567;
echo $var; // 4536695
echo json_encode($var); // 4536695
echo json_decode(4536695); // 4536695
echo json_decode($var); // 4536695
$var = 21234567;
echo $var; // 21234567
echo json_encode($var); // 21234567
echo json_decode(4536695); // 21234567
echo json_decode($var); // 21234567
so, the integer value should return false when i check json encoded string with isJson function. but it is not.
If 021234567 is string. when i use json_encode i should got "021234567" (with double quote). if this string has no double quote, it should not be json encoded.
$var = '021234567';
echo $var; // 021234567
echo json_encode($var); // "021234567"
echo json_decode('"021234567"'); // 021234567
echo json_decode($var); // 21234567
// example if string is text with double quote in it.
$var = 'i"m sam';
echo $var; // i"m sam
echo json_encode($var); // "i\"m sam"
echo json_decode('"i\"m sam"'); // i"m sam
echo json_decode($var); // null
As you see. the simple string with json encoded should contain at least double quote character at open and close of that string.
Please help me how to check that string is valid json encoded.
I think the valid json encoded string should at least have double quote "
or curly bracket {}
at the open and close of that string.
I don't know how to check that or don't know how to preg_match that.