Skip to content

How to check is a string valid json in PHP ?

Last updated on November 28, 2022

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate & JSON is language-independent.

PHP has 4 built-in JSON functions called json_encode(), json_decode(),json_​last_​error_​msg(),json_​last_​error().

json_encode() & json_decode(): This function is used for encoding and decoding in JSON format.

json_​last_​error_​msg() & json_​last_​error() : This function are use full after json_encode() or json_decode() call. json_​last_​error_​msg() function returns the error string, and json_​last_​error() Returns an integer which can be found in the PHP Manual. for no error checking we can compare with JSON_ERROR_NONE constant.

JSON Encode:

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
// output : {"a":1,"b":2,"c":3,"d":4,"e":5}

JSON Decode:

$array= array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$encoded_data = json_encode($array);
// output : {"a":1,"b":2,"c":3,"d":4,"e":5}
$decoded_data = json_decode($encoded_data);
// output : stdClass Object ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 ) 

//To Decode as Array set second parameter ture
$decoded_data = json_decode($encoded_data,true);
//  output : Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 ) 

Check for valid JSON

we can use the json_last_error() PHP function to check the validity of JSON, It returns JSON_ERROR_NONE predefined constant value if JSON is successfully decoded or encoded by PHP’s JSON functions.

function is_json($string,$return_data = false) {
	  $data = json_decode($string);
     return (json_last_error() == JSON_ERROR_NONE) ? ($return_data ? $data : TRUE) : FALSE;
}

How to use the is_json function:

$response = is_json('{"a":1,"b":2,"c":3,"d":4,"e":5}',TRUE);
print_r($response);
//output : stdClass Object ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 ) 

$response = is_json('{"a":1,"b":2,"c":3,"d":4,"e":5}');
print_r($response);
// output : 1

That’s all for today I hope you like this tutorial please don’t forget to give me your feedback.

3.3 3 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments