How to Validate JSON String in PHP

yotube
0

Hi, we'll see how to validate json string in this PHP tutorial. JSON is a light-weight data exchange format among web services and it is very human readable. At times it is required to check if the json output you received is a valid one. PHP programming language does not provide any direct method to validate a json string but sure there is some workaround to determine if a string is a valid json format or not. You need PHP version 5.3 or above for this to work out.

php-validate-json-string-format

There are 4 built-in functions provided by PHP to deal with json format namely json_encode(), json_decode(), json_last_error_msg() and json_last_error().

The methods json_encode() and json_decode() are used to encode and decode json format and the working example of them are already covered in this blog.

The other two methods json_last_error_msg() and json_last_error() should be used in conjunction with the json encode or decode methods.

How to Validate JSON String in PHP?

The php function json_last_error() takes no parameters and returns the error (in case) encountered during the last json encoding/decoding process. If there is no error then it returns an integer constant "JSON_ERROR_NONE". Check here for the complete list of error constants returned by this method.

So by decoding the given string and checking it for errors, we can determine if it's a valid json string or not.

Here is the php code to validate json string.

PHP Function to Validate JSON


<?php
function validate_json($str=NULL) {
if (is_string($str)) {
@json_decode($str);
return (json_last_error() === JSON_ERROR_NONE);
}
return false;
}
?>

Function Usage

You can use the above function validate_json() like below to determine a valid json string.


<?php
echo (validate_json('{"format": "json"}') ? "Valid JSON" : "Invalid JSON");
// prints 'Valid JSON'
echo (validate_json('{format: json}') ? "Valid JSON" : "Invalid JSON");
// prints 'Invalid JSON'
echo (validate_json(array()) ? "Valid JSON" : "Invalid JSON");
// prints 'Invalid JSON'
echo (validate_json() ? "Valid JSON" : "Invalid JSON");
// prints 'Invalid JSON'
?>
Read:

Thus with a small workaround you can validate a json string easily in php.

Tags

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top