• Reading time ~ 5 min
  • 20.04.2023

Introduction

There may be times when you're building your Laravel application that you need to read a JSON file.

I've often found myself needing to do this when I'm writing tests for an API integration and I want to read a dummy response that I'd previously saved in a JSON file. I've also needed to do this when I've been working with third-party services (such as Firebase) that provide a JSON file for you to pass to an SDK for authentication.

In this Quickfire article, we're going to quickly cover how to use a new File::json method that was added in Laravel 10.4 by Austin White in PR #46481. We'll also cover how to use the similar Storage::json method that was added in Laravel 10.5 by lorenzolosa in PR #46548.

We'll then quickly compare the differences between the two methods and how to improve the error handling.

Reading JSON Files Using the "File" Facade

The File::json method is a simple wrapper around the json_decode function and File::get method. It allows you to read a JSON file from your local filesystem and return the contents as an array.

Previously, if you wanted to read a JSON file in your Laravel app, you could do something like this:

$contents = File::get(base_path('path/to/file.json'));
$json = json_decode($contents);

Assuming the JSON file is valid, the $json variable would now be an array containing the contents of the JSON file.

For example, let's say the JSON file contained the following data:

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ]
}

The $json variable would now contain the following array data:

[
    'name' => 'laravel/laravel',
    'type' => 'project',
    'description' => 'The Laravel Framework.',
    'keywords' => [
        'framework',
        'laravel',
    ],
]

We can achieve the exact same behaviour by using the new File::json method like so:

$json = File::json(base_path('path/to/file.json'));

Although this is a small change, I really like it!

I'm a huge fan of trying to make my code read as close to plain English as possible, and I feel like this method helps with that. Whenever I write any code, I try and think to myself, "Would a junior joining the team be able to understand what's going on?".

Of course, this one small change isn't going to make your code magically readable to everyone, but I think it's small changes like these that give you marginal gains over time.

Reading JSON Files Using the "Storage" Facade

Similar to the File::json method, Laravel also has a Storage::json method that you can use to read JSON files.

Whereas the File::json method can be used to read JSON files from anywhere on your local filesystem, the Storage::json method can be used to read files from your application's storage disk. As a result, this means you can use Storage::json for reading files from an AWS S3 bucket, Digital Ocean Spaces, and so on.

You can call the method in the exact same way as the File::json method:

$json = Storage::json('path/to/file.json');

Error Handling

Different Behaviours for Non-Existent Files

At the time of writing this article, it's important to note that the File::json and Storage::json have slightly different behaviour when it comes to dealing with non-existent files.

If you try to read a non-existent file using the File::json method, it will throw a Illuminate\Contracts\Filesystem\FileNotFoundException exception. However, if you try to read a non-existent file using the Storage::json method, it will return null.

This is something that you'll need to remember when using these methods and deciding the best approach for error handling.

Reading Invalid JSON Files

You must always remember to validate the contents of a JSON file before you try and use it.

Let's say you have the following invalid JSON file (that has a trailing comma on the second-to-last line to cause an error):

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
}

If you tried to use Storage::json or File::json to read this file, both of these methods would return null. This is because the json_decode function will return null if it's unable to decode the JSON string.

This is due to the fact that the underlying json_decode method uses 0 (JSON_ERROR_NONE) as the default flag which means that it will silently fail if it encounters an error.

Typically, I prefer an exception to be thrown if there's an error so that I'm forced to handle it. It ensures that I won't be using invalid data in my application and can alert me on my bug-tracking software so I can fix the issue. To do this you can pass the JSON_THROW_ON_ERROR flag to the methods like so:

$json = Storage::json('path/to/file.json', JSON_THROW_ON_ERROR);

$json = File::json('path/to/file.json', JSON_THROW_ON_ERROR);

Now, if either of those methods are unable to decode the JSON string, a JsonException will be thrown.

Conclusion

Hopefully, this Quickfire article should have given you a quick insight into how you can use the new File::json and Storage::json methods to read JSON files in Laravel.

If you enjoyed reading this post, I'd love to hear about it. Likewise, if you have any feedback to improve the future ones, I'd also love to hear that too.

You might also be interested in checking out my 220+ page ebook "Battle Ready Laravel" which covers similar topics in more depth.

If you're interested in getting updated each time I publish a new post, feel free to sign up for my newsletter below.

Keep on building awesome stuff! 🚀

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297