Fermin Perdomo
Full Stack Developer
© 2024 Fermin's Portfolio | All rights reserved.
Simplify Your JSON File Processing with Simple JSON in PHP
If you frequently work with JSON files, you know how important it is to have a reliable and efficient way to read and write them. The new Simple JSON package makes this easy with its simple and intuitive interface.
One of the key features of Simple JSON is its use of generators to minimize memory usage, even when dealing with large files. This means you can process your JSON files quickly and efficiently, without worrying about running out of memory.
Here's an example of how to read a JSON file with Simple JSON:
use DiamondDove\SimpleJson\SimpleJsonReader;
SimpleJsonReader::create('users.json')->get()
->each(function(array $user) {
// process the row
});
Installation
You can install the package using composer:
composer require diamond-dove/simple-json
Usage
Reading a JSON file
To read a JSON file, you can use the following code:
use DiamondDove\SimpleJson\SimpleJsonReader;
// $records is an instance of Illuminate\Support\LazyCollection
$records = SimpleJsonReader::create($pathToJson)->get();
$records->each(function(array $user) {
// in the first pass $user will contain
// ['email' => '[email protected]', 'first_name' => 'john']
});
Writing a JSON file
To write a JSON file, you can use the following code:
Use DiamondDove\SimpleJson\SimpleJsonWriter;
$writer = SimpleJsonWriter::create($pathToJson)
->push([
['first_name' => 'John', 'last_name' => 'Doe'],
['first_name' => 'Jane', 'last_name' => 'Doe'],
]);
The file at $pathToJson
will contain:
[
{"first_name": "John", "last_name": "Doe"},
{"first_name": "Jane", "last_name": "Doe"}
]