loophp/collection

Parse JSON in a lazy way

drupol opened this issue · 0 comments

This morning I discovered this: https://packagist.org/packages/halaxa/json-machine

I think we should provide an example and documentation on how to use it with this collection library.

Something like this?

With Guzzle:

<?php

require_once __DIR__ . '/../../vendor/autoload.php';

$client = new \GuzzleHttp\Client();
$response = $client->request('GET', $file);
$phpStream = \GuzzleHttp\Psr7\StreamWrapper::getResource($response->getBody());

$json = Collection::fromIterable(\JsonMachine\JsonMachine::fromStream($phpStream));

foreach ($json as $key => $value) {}

With Symfony client:

<?php

/**
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

declare(strict_types=1);

namespace App;

use JsonMachine\JsonMachine;
use loophp\collection\Collection;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\ChunkInterface;

include __DIR__ . '/vendor/autoload.php';

$file = 'https://httpbin.org/anything';
//$file = 'https://github.com/json-iterator/test-data/blob/master/large-file.json?raw=true';

$client = HttpClient::create();
$response = $client->request('GET', $file);

$json = Collection::fromIterable(
        JsonMachine::fromIterable(
            Collection::fromIterable($client->stream($response))
                ->map(
                    static function(ChunkInterface $chunk): string {
                        return $chunk->getContent();
                    }
                )
        )
    );

foreach ($json as $key => $value) {}