PHP code to check if a string is valid JSON or not

json_logo-555px__1_

A function to check if a string is valid JSON (JavaScript Object Notation) or not. It takes json string as a parameter and returns true if valid, otherwise false.


function isValidJson($string){
$json = json_decode($string);
return (is_object($json) && json_last_error() == JSON_ERROR_NONE) ? true : false;
}

#How to use
if(isValidJson('{"a":1}')){
echo "Valid Json";
}else{
echo 'Invalid Json' ;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s