The quickest method to verify if a string is JSON using PHP is to use the built-in function json_decode()
. This function parses a JSON string and returns the decoded data, or null
if the JSON is invalid.
Therefore, to verify if a string is JSON, you can simply call json_decode()
with the string as argument and check if the result is not equal to null
. Here's an example:
function isJson(string $string) : bool {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
This function returns true
if the string is valid JSON, or false
otherwise.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-12-22 11:00:00 +0000
Seen: 8 times
Last updated: Apr 01
How can a HTTP header be inserted in WordPress?
How can data be stored in a data attribute and utilized through Ajax?
How can an array be passed using typo3 flexform xml and itemsProcConfig?
How to use Composer autoload in implementing PHP namespaces?
What is the difference between highlighting HTML code in a .php file in VSCode?
Does JSON encode fail to retrieve data from the database?
Why isn't the cell text appearing when using easytable and fpdf in PHP version 7.4?
Can the GS1 128 barcode decoder in PHP or Jquery be utilized?
How can Xdebug be used in conjunction with VSCode for Laravel on Sail and WSL2?