Vittorio Emmermann
Posted on May 25, 2020
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:
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.
Posted on May 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024