How can I check if it is a valid json before it has been decoded, like in case of an array we can check with is_array(); can we do something similar in PHP?
Asked
Active
Viewed 6,760 times
1 Answers
-1
First decode
the string
with oppressor
. If it gives true
then it is valid else
invalid. Also cane use json_last_error(). You can check by this way..
$str = 'your json string';
$test = @json_decode($str);
if($test){
echo 'Valid';
}else{
echo 'not valid';
}

MH2K9
- 11,951
- 7
- 32
- 49
-
-
2That by itself it not really enough. `[]` is a valid JSON string but would fail your test. The return value is not "`true`", it's the decoded value, which could be a number of things. There's no need for `@` either, since `json_decode` doesn't trigger warnings AFAIK. – deceze Sep 07 '14 at 13:18
-
Hello, i want to check before it has been decoded. Your solution checks if the decoded value is present or not. – Shirshak Sep 07 '14 at 13:24
-
1What would be the purpose of checking before decoding exactly? I suppose you would want to decode and use it if it is valid, no? – CBroe Sep 07 '14 at 13:31
-
Helo, In same db column there is JSON and other normal string aswell. So it's tryig to decode normal string aswell, and its showing error. So i want to check if it is just JSON and do other stuff. – Shirshak Sep 07 '14 at 13:38