How to check if a string is valid JSON in Laravel

Categorized as Laravel

It is very common when you have to check whether a string is a valid JSON or not.

An example of Str::isJson in Laravel

In Laravel, you may want to use Str::isJson method as follows:

use Illuminate\Support\Str;

Str::isJson($data);

Str::of($data)->isJson();

str($data)->isJson();

These are examples from the official documentation:

$result = Str::isJson('[1,2,3]');
// true
 
$result = Str::isJson('{"first": "John", "last": "Doe"}');
// true
 
$result = Str::isJson('{first: "John", last: "Doe"}');
// false

What is JSON for?

JSON is a data format that helps exchange data between web apps and servers. It is a lightweight, human-readable (arguably), and easy-to-understand format. It is used in many web frameworks and applications, such as Laravel, WordPress, and in mobile app development.

Leave a reply

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