- PHP RFC: is_json
- Proposal
- Description
- Parameters
- Return values
- Extra behavior
- Examples
- Fundaments/Reasons
- Disadvantages of using json_decode
- Disadvantages of using regex
- Needs from major projects and developers
- Complexity added in the core
- Backward Incompatible Changes
- Proposed PHP Version(s)
- RFC Impact
- PHP RFC: json_validate
- Proposal
- Description
- Parameters
- Return values
- Examples
- General notes from discussion of the RFC
- Use cases contributed by the community
- Reasons to have json_validate() function in the core
- Disadvantages of using json_decode to only validate a json-string
- Disadvantages of using regex
- Disadvantages of userland solutions
- PHP already has a JSON parser
- Needs from major projects and developers
- Complexity added in the core
- Reasons NOT to have json_validate() function in the core
- Changes in the RFC that happened during discussion
- Throw Exception on error
- Others
- Backward Incompatible Changes
- Proposed PHP Version(s)
- RFC Impact
- Future Scope
- How to check is a string valid json in PHP ?
- JSON Encode:
- JSON Decode:
- Check for valid JSON
- How to use the is_json function:
- How to Validate JSON String in PHP
- How to Validate JSON String in PHP?
- PHP Function to Validate JSON
- Function Usage
PHP RFC: is_json
This RFC introduces a new function called is_json() to validate if an string contains a valid json.
Most userland implementations to achieve this are done using json_decode() which by design generates an object/array while parsing the string, ergo using memory and processing, that could be save.
Proposal
Description
is_json(string $json, int $depth = 512, int $flags = 0): bool
Parameters
The json string being analyzed.
This function only works with UTF-8 encoded strings.
PHP implements a superset of JSON as specified in the original » RFC 7159.
Maximum nesting depth of the structure being decoded.
Bitmask of JSON_INVALID_UTF8_IGNORE, JSON_THROW_ON_ERROR. The behavior of these constants is described on the JSON constants page.
Function description, examples, technical strategy, current JSON parser, etc.
Return values
Returns true if the string passed contains a valid json, otherwise returns false.
Extra behavior
Examples
Fundaments/Reasons
Disadvantages of using json_decode
By design, json_decode() generates an object/array while parsing the string, ergo using memory and processing for it, that is not needed if the only thing to discover is if a string contains a valid json.
Disadvantages of using regex
Using a regex for this task forces different, error-prone, hard to maintain, implementations.
Needs from major projects and developers
In the “References” section, there is a list of major open-source php projects needing this feature; also in th mntioned section can find a link to one of the most popular StackOverflow questions, which somehow reflects the need from our developers to have a feature like this included.
Complexity added in the core
At the moment, there is a JSON parser in the core, used by json_decode to do its job, so there is no need to write a new JSON parser for this RFC ; the proposed function will use the existing JSON parser exclusively to parse an string without generating any object/array in memory for it.
Backward Incompatible Changes
None, as this is a new function only.
is_json will no longer be available as a function name, could break potential userland implementations.
Proposed PHP Version(s)
RFC Impact
This RFC has no impact on SAPIs, existing extensions, Opcache, etc.
PHP RFC: json_validate
This RFC introduces a new function called json_validate() to validate if an string contains a valid json.
Most userland implementations use json_decode() which by design generates a ZVAL(object/array/etc.) while parsing the string, ergo using memory and processing that could be save.
The proposed function will use the exact same JSON parser that already exists in the PHP core, which is also use by json_decode(), this garantees that what is valid in json_validate() is also valid in json_decode().
Proposal
Description
json_validate(string $json, int $depth = 512, int $flags = 0): bool
Parameters
The json string being analyzed.
This function only works with UTF-8 encoded strings.
PHP implements a superset of JSON as specified in the original » RFC 7159.
Maximum nesting depth of the structure being decoded.
Bitmask of JSON_INVALID_UTF8_IGNORE. The behavior of this constant is described on the JSON constants page.
Return values
Returns true if the string passed contains a valid json, otherwise returns false.
Examples
1. Validate a valid json-string
2. Validate an invalid json-string
Errors during validation can be fetch by using json_last_error() and/or json_last_error_msg().
General notes from discussion of the RFC
Different users have tested the functionality and obtained the promised results. Also their feedback about it was positive.
Most part of the community in the mailing list showed a positive opinion about this RFC , and looks forward for its integration into PHP.
The ones that checked the code also agree that is small implementation, easy to maintain, and at the same time provides a big benefit for such small implementation.
The community got involve very actively in the discussion of the RFC and provided all kind of useful feedback, and also took the time to test json_validate() by themselves.
Use cases contributed by the community
Eventhough not reduce to only these examples, during discussion in mailing list, some users expressed:
“Yes well-formed JSON from a trusted source tends to be small-ish. But a validation function also needs to deal with non-well-formed JSON, otherwise you would not need to validate it.”
“If with a new function (json_validate()) it becomes much easier to defend against a Denial-of-Service attack for some parts of a JSON API , then this can be a good addition just for security reasons.”
“fast / efficient validation of a common communication format reduces the attack surface for Denial-of-Service attacks.”
Reasons to have json_validate() function in the core
Based on discussion of the RFC in the mailing list
Disadvantages of using json_decode to only validate a json-string
By design, json_decode() generates a ZVAL (object/array/etc.) while parsing the string, ergo using memory and processing for it, that is not needed if the only thing to discover is if a string contains a valid json or not.
Disadvantages of using regex
Using a regex for this task forces different, error-prone, hard to maintain, implementations.
Disadvantages of userland solutions
They need to be up-to-date with the existing PHP JSON parser used by json_decode() already, otherwise a json-string valid in userland solution might not be valid json-string for json_decode() or vice-versa.
PHP already has a JSON parser
As previously mentioned, PHP already has a JSON parser used by json_decode(). The proposed function will use that parser, guaranteeing 100% compatibility between json_decode() and json_validate()
Needs from major projects and developers
In the “References” section, there is a list of major open-source php projects that could benefit with this new function.
Also in the mentioned section a link to one of the most popular StackOverflow questions is provided, which somehow reflects the need from our developers to have a feature like this included.
Please check the “References” section.
Complexity added in the core
At the moment, there is a JSON parser in the core, used by json_decode() to do its job, so there is no need to write a new JSON parser for this RFC ; the proposed function will use the existing JSON parser exclusively to parse an string without generating any object/array/etc. in memory for it.
Reasons NOT to have json_validate() function in the core
One member of the mailing list expressed that:
“If we keep the tendency to pollute already bloated standard library with an army of small functions that could have not exists and be replaced with normal PHP counterparts IMHO we’ll end with frustration from developers as I believe DX slowly falls down here.”
“A `json_decode()` is a substitute that IMO solves 99% of use cases. If I’d follow your logic and accept every small addition that handles 1% of use cases, somebody will raise another RFC for simplexml_validate_string or yaml_validate and the next PhpToken::validate. All above can be valid if we trust that people normally validate 300MB payloads to do nothing if they DON’T fail and there is nothing strange about that.”
The user also provided an implementation of a JSON parser written in pure PHP. https://gist.github.com/brzuchal/37e888d9b13937891c3e05fead5042bc
Changes in the RFC that happened during discussion
Throw Exception on error
In my initial implementation, the developer had the option to provide a flag to indicate that in case of error during validation an exception should be throw.
The ability to throw an exception on error was removed from the implementation, as this was pointed not only by most of user in the mailing list (with good reasons), but also during code review; as it does not make sense to have such a behavior.
I also have to admit that after they showed their arguments, I changed my mind, and now I also think it makes sense to have such a behavior in the function.
So removing the ability to throw exception on error was removed from implementation.
Others
I removed 3 of the originally provided examples in the RFC because did not adjust to the RFC purpose or were not clear.
I had to adjust the wording in this RFC document regarding disadvantage of using json_decode() as pointed here:
Backward Incompatible Changes
None, as this is a new function only.
json_validate will no longer be available as a function name.
Proposed PHP Version(s)
RFC Impact
This RFC has no impact on SAPIs, existing extensions, Opcache, etc.
Future Scope
— (To be defined by future discussions if needed)
How to check is a string valid json in PHP ?
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 :
JSON Decode:
$array= array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); $encoded_data = json_encode($array); // output : $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)
How to use the is_json function:
$response = is_json('',TRUE); print_r($response); //output : stdClass Object ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 ) $response = is_json(''); 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.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face — we are here to solve your problems.
How to Validate JSON String in PHP
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.
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
Function Usage
You can use the above function validate_json() like below to determine a valid json string.
') ? "Valid JSON" : "Invalid JSON"); // prints 'Valid JSON' echo (validate_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' ?>
Thus with a small workaround you can validate a json string easily in php.