How to validate JSON in Laravel — Amit Merchant — A blog on PHP, JavaScript, and more

0
18

I’m pretty sure if you’re older enough to be working in the software development industry, the one format that you would be working with in a recurring manner is JSON.

There are a lot of places where information is represented as JSON and when you’re working with JSON, it’s important that it’s not an invalid one to keep systems’ integrity intact.

Now, Laravel makes it pretty easy to validate JSON strings with the newly added isJson method in Laravel 9.x.

So, for instance, let’s say we have the following JSON…

$user = '
  "name": "Cherika",
  "age": 5,
  "is_active": false
';

… And if we want to validate this JSON string, here’s how we can do it.

use IlluminateSupportStr;

$isValidUser = Str::isJson($user); 
// boolean (true)

The method is also available when you’re working with fluent strings.

$isValidUser = Str::of($user)->isJson(); 
// boolean (true)

$isValidUser = str($user)->isJson(); 
// boolean (true)

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here