cerbero / lazy-json
Load heavy JSON in Laravel lazy collections.
Fund package maintenance!
cerbero90
Installs: 155 105
Dependents: 2
Suggesters: 0
Security: 0
Stars: 156
Watchers: 3
Forks: 3
Open Issues: 0
Requires
- php: ^7.2||^8.0
- halaxa/json-machine: ^0.7
- illuminate/support: >=6.0
Requires (Dev)
- guzzlehttp/guzzle: ^7.0
- mockery/mockery: ^1.3.4
- orchestra/testbench: >=3.9
- phpunit/phpunit: >=8.0
- squizlabs/php_codesniffer: ^3.0
Suggests
- guzzlehttp/guzzle: Required to load JSON from endpoints (^7.0).
This package is auto-updated.
Last update: 2023-01-13 09:58:39 UTC
README
Framework agnostic package to load heavy JSON in lazy collections. Under the hood, the brilliant JSON Machine by @halaxa is used as a lexer and parser.
Need to load paginated items of JSON APIs? Consider using Lazy JSON Pages instead.
Install
In a Laravel application, all you need to do is requiring the package:
composer require cerbero/lazy-json
Otherwise, you also need to register the lazy collection macro manually:
use Cerbero\LazyJson\Macro; use Illuminate\Support\LazyCollection; LazyCollection::macro('fromJson', new Macro());
Usage
Loading JSON in lazy collections is possible by using the collection itself or the included helper:
LazyCollection::fromJson($source); lazyJson($source);
The following are the supported JSON sources:
$source = '{"foo":"bar"}'; // JSON string $source = ['{"foo":"bar"}']; // any iterable containing JSON, i.e. array or Traversable $source = 'https://foo.test/endpoint'; // endpoint $source = Http::get('https://foo.test/endpoint'); // Laravel HTTP client response $source = '/path/to/file.json'; // JSON file $source = fopen('/path/to/file.json', 'rb'); // any resource $source = <Psr\Http\Message\MessageInterface>; // any PSR-7 message, e.g. Guzzle response $source = <Psr\Http\Message\StreamInterface>; // any PSR-7 stream
Optionally, you can define a dot-noted path to extract only a sub-tree of the JSON. For example, given the following JSON:
{ "data": [ { "name": "Team 1", "users": [ { "id": 1 }, { "id": 2 } ] }, { "name": "Team 2", "users": [ { "id": 3 } ] } ] }
defining the path data.*.users.*.id
would iterate only user IDs:
$ids = lazyJson($source, 'data.*.users.*.id') ->filter(fn ($id) => $id % 2 == 0) ->all();
Change log
Please see CHANGELOG for more information on what has changed recently.
Testing
composer test
Contributing
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
Security
If you discover any security related issues, please email andrea.marco.sartori@gmail.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.