Check if a string is valid JSON in php

A little 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 it is valid otherwise returns false.

If you want to Create a JSON string from mysql database you may visit here.

 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' ; 
 }


Check if a string is valid JSON in php Check if a string is valid JSON in php Reviewed by JS Pixels on June 29, 2014 Rating: 5

No comments:

Altaf Web. Powered by Blogger.