DEV Community

Cover image for Quick Tip: Creating pretty JSON files with Laravel
Vittorio Emmermann
Vittorio Emmermann

Posted on • Originally published at vittorio.dev

Quick Tip: Creating pretty JSON files with Laravel

Often I had a situation where my Apps had to generate a JSON file. For example, I'd write a CLI App for package development. This package had to write JSON pretty formatted to the generated composer JSON.

Here is a quick hint of how to generate this JSON string nice and smooth with laravel:

$json = Collection::make([
    'name' => 'Test',
    'description' => 'Another awesome laravel package',
    'license' => 'MIT'
  ])->toJson(JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

This snipped will give you a $json Variable, which you can print to a file without any stress. It's pretty, escaped and with all formattings you need. We work here with Collection, a class from Laravel itself. Before using it you have to import it at the top of your file:

use Illuminate\Support\Collection;

For the example above, see here the output:

JSON Preview

That's it for now. With this variable you can print in files like a CloudFront Configuration, a composer.json for code generation or other things devs need for all-day work.

Top comments (0)