Nov 23, 2016
2 mins read
This article is about to validate JSON String using PHP. JSON is the popular data format to transfer data between client and server. There are many JSON validators are available online such as [JSON Validator][1] and [JSON Validator on CodeBeautify][2] to validate JSON.
As a programmer, I am curious to know how these tools are working. Here I am going to explain.
json_decode() is the function which is been introduce in PHP 5.3 to validate JSON String.
Here is the description is given in PHP specification.
mixed json_decode ( string [, bool = false [, int = 512 [, int = 0 ]]] )
This function takes a JSON encoded the string and converts it into a PHP variable.
Here is the function which works as JSON Validator.
|
|
Let’s see how does this work.
if (!empty($data))
This condition will check the $data variable is not empty. If $data is empty, then it will return false.
@json_decode($data)
json_decode parses the data and return the PHP variable if the string is valid. If the string is not valid it will generate the error. Character “@” will suppress the error.
return (json_last_error() === JSON_ERROR_NONE);
This will check if $data is valid JSON string by comparing with JSON_ERROR_NONE. json_last_error() return the last error when json_decode() has called if there are any.
Here is the Example of Validating JSON data.
|
|
Related Articles:
Validate JSON String using JavaScript
Related Tools:
Sharing is caring!