Skip to content

Commit

Permalink
Add lazy JSON parsing examples using @halaxa JsonMachine library.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed May 22, 2021
1 parent 7b4196a commit c3744ca
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
63 changes: 63 additions & 0 deletions docs/pages/code/lazy-json-parsing.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?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;

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

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

/**
* In order to get this working, you will need the library halaxa/json-machine.
* Use composer to install it in your project.
*
* composer require halaxa/json-machine
*
* halaxa/json-machine is a lazy JSON parser and it is fully compatible
* with loophp/collection.
*/

// Parse a local JSON file
$composerJson = __DIR__ . '/../../../composer.json';

$json = Collection::fromIterable(JsonMachine::fromFile($composerJson));

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

$remoteFile = 'https://httpbin.org/anything';

// Parse a remote JSON file with Guzzle
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', $remoteFile);
$phpStream = \GuzzleHttp\Psr7\StreamWrapper::getResource($response->getBody());

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

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

// Parse a remote JSON file with Guzzle
$client = HttpClient::create();
$response = $client->request('GET', $remoteFile);

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

foreach ($json as $key => $value) {
}
6 changes: 6 additions & 0 deletions docs/pages/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,9 @@ Read a file

.. literalinclude:: code/read-file.php
:language: php

Lazy json parsing
~~~~~~~~~~~~~~~~~

.. literalinclude:: code/lazy-json-parsing.php
:language: php

0 comments on commit c3744ca

Please sign in to comment.