How to Validate JSON String in PHP

JSON stands for JavaScript Object Notation, It is based on a subset of the JavaScript Programming Language and it is easy for humans to read and write. Also, JSON is language independent. It is a lightweight format for storing and transporting data among web services. However, it is most important to validate the JSON data while receiving it. But PHP does not provide any direct method to validate a JSON string. So here I am going to show you how to validate the JSON string in PHP.

By default, PHP has four in-built JSON functions named json_encode(), json_decode(), json_​last_​error_​msg() and json_​last_​error().

  • json_encode() is used to encode a value to JSON format.
  • json_decode() is used to decode/convert a JSON object to a PHP object/array.
  • json_​last_​error_​msg() & json_​last_​error(), this functions will be used after json_encode() or json_decode() call. json_​last_​error_​msg() function will be returned the error as a string, json_​last_​error() will be returned the error as an integer.

Here is the example PHP code to validate the JSON string by using the above PHP functions,

<?php
$string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

json_decode($string);

switch (json_last_error()) {
	case JSON_ERROR_NONE:
		echo 'No errors';
		break;

	case JSON_ERROR_DEPTH:
		echo 'Maximum stack depth exceeded';
		break;

	case JSON_ERROR_STATE_MISMATCH:
		echo 'Underflow or the modes mismatch';
		break;

	case JSON_ERROR_CTRL_CHAR:
		echo 'Unexpected control character found';
		break;

	case JSON_ERROR_SYNTAX:
		echo 'Syntax error, malformed JSON';
		break;

	case JSON_ERROR_UTF8:
		echo 'Malformed UTF-8 characters, possibly incorrectly encoded';
		break;

	default:
		echo 'Unknown error';
		break;
}

In the above code,

  • The function json_decode($string) is used to decode the JSON string and it will be returned the PHP object.
  • The function json_last_error() will be returned the error message if the JSON string is not valid.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *