Core\Json::encodeEach
Core\Json::encodeEach(
array<mixed>|Iterable<mixed>|Iterator<mixed> $items,
{lines?: bool},
): Core\Json\Pieces<bytes>Writes a JSON array in pieces, so a long list never has to be in memory as one string.
Core\Json::encodeEach takes an array or an iterable, such as the rows of a database query. It returns pieces of at most 64 KiB that you read with a foreach loop. It takes the next item only when it needs it.
Each item is encoded as Core\Json::encode encodes it. The pieces are bytes. If an item can contain tainted text, such as a value from a request, the pieces are tainted bytes.
Set lines to true to write JSON Lines, with one value on each line.
To send the pieces as a response, pass each one to the write method of Core\Response::startStream('application/json'). write does not accept tainted pieces. To write the pieces to a file, use Core\IO::writeStream($path, $pieces).
Good to know: if an item throws an error halfway, your loop may already have received some pieces.
Parameters
$itemsarray<mixed>|Iterable<mixed>|Iterator<mixed>The values to write. It can be an array or an iterable, such as a database stream.
Options
linesbooloptionalWhentrue, it writes JSON Lines: one value on each line, with no brackets and no commas. The default isfalse.
Return value
Returns Core\Json\Pieces<bytes>. The JSON text as bytes, in pieces of at most 64 KiB. The first piece starts with [ and the last piece ends with ]. Nothing is encoded until the loop starts. If an item can contain tainted text, the pieces are tainted bytes, as the result of encode is a tainted string.
Errors
LogicErrorAn item contains something that JSON cannot represent, as forencode. The error is thrown when the loop reaches that item. Your loop may already have received some pieces. Only complete pieces reach the loop, so the text of earlier items that was not yet in a piece is lost.
Examples
Answer with a filtered list
<?nvs// Shows a request that gets back the products in stock, as a JSON array sent in pieces.
#[Core\Json\Derive]class Product{ public string $sku; public int $stock;
public function constructor(string $sku, int $stock) { $this->sku = $sku; $this->stock = $stock; }}
class Stock{ // This function gives the products in stock, one at a time. public static function available(): Iterator<Product> { array<Product> $all = [new Product('MUG-01', 12), new Product('LID-02', 0), new Product('CUP-07', 30)]; foreach ($all as Product $product) { if ($product->stock > 0) { yield $product; } } }}
// `Core\Response::startStream` starts the body and sets its content type to `application/json`.Core\Response\Stream $out = Core\Response::startStream('application/json');
// The pieces are `bytes`, because no product contains text from a request.// This sends `[{"sku":"MUG-01","stock":12},{"sku":"CUP-07","stock":30}]`.foreach (Core\Json::encodeEach(Stock::available()) as bytes $piece) { $out->write($piece);}[{"sku":"MUG-01","stock":12},{"sku":"CUP-07","stock":30}]Export a table to a file
<?nvs// Shows how to export a database table to a JSON file, one row at a time.
// `Core\Db\Derive` fills the class from a row. `Core\Json\Derive` writes it as a JSON object.#[Core\Db\Derive]#[Core\Json\Derive]class Order{ public uint $id; // A text column arrives as `tainted`, because the value comes from the database. public tainted string $customer; public int $cents;
public function constructor(uint $id, tainted string $customer, int $cents) { $this->id = $id; $this->customer = $customer; $this->cents = $cents; }}
// `:memory:` is a database that lasts as long as the program runs.var $db = Core\Db::open({ driver: Core\Db\Driver::Sqlite, path: ':memory:' });$db->execute('create table orders (id integer primary key, customer text not null, cents integer not null)', []);$db->execute('insert into orders (customer, cents) values (?, ?), (?, ?), (?, ?)', ['Ada', 2500, 'Ben', 1200, 'Cleo', 900]);
// `queryEachAs` reads one row at a time. `encodeEach` takes the next row only when it needs it.// So you can export a table that is larger than memory.var $orders = $db->queryEachAs<Order>('select id, customer, cents from orders order by id', []);string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'orders.json');Core\IO::writeStream($path, Core\Json::encodeEach($orders), { overwrite: true });
$db->close();
// This prints the JSON array with the three orders.echo Core\IO::read($path), "\n";[{"id":1,"customer":"Ada","cents":2500},{"id":2,"customer":"Ben","cents":1200},{"id":3,"customer":"Cleo","cents":900}]Write events as json lines
<?nvs// Shows how to write a list of events as JSON Lines, one JSON object on each line.
array<{ event: string, user: string }> $events = [ { event: 'login', user: 'ada' }, { event: 'upload', user: 'ada' }, { event: 'logout', user: 'ben' },];
// `{ lines: true }` writes each item on its own line, with no `[` and no commas between items.string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'events.jsonl');Core\IO::writeStream($path, Core\Json::encodeEach($events, { lines: true }), { overwrite: true });
// This prints three lines. Another program can add a line to the file without reading it first.echo Core\IO::read($path);{"event":"login","user":"ada"}{"event":"upload","user":"ada"}{"event":"logout","user":"ben"}