Core\Json::decodeEach
Core\Json::decodeEach<T>(
Core\Bytes::Source|Core\Bytes::Chunks $source,
string $at = "",
{lines?: bool, maxDepth?: uint},
): Core\Json\Elements<T>Reads a JSON array one element at a time, so the whole document never has to be in memory.
Core\Json::decodeEach<T> reads from an open file, an uploaded file, Core\Request::bodyStream(), bytes, or a list or loop that gives bytes pieces. You read the result once, with a foreach loop. Every step gives you one element, checked as Core\Json::decodeAs<T> checks a document. Write mixed as T to get plain values. Each string in them is then tainted. With a shape or a #[Json\Derive] class, a string property is a plain string, and a tainted string property is tainted. A class inside a shape or an array needs #[Core\Json\Derive] too, however deep it is.
The second argument is a JSON Pointer: a path such as /orders to an array inside the document. The default '' reads the document itself. Set lines to true to read JSON Lines, with one value on each line. The pointer must then be ''.
An error halfway throws a ParseError with the byte offset of the error. Your loop already has the elements before it.
Good to know: decodeEach does not close the file. Close it yourself.
Parameters
$sourceCore\Bytes::Source|Core\Bytes::ChunksThe JSON to read. It isbytes, an openCore\IO\File, an uploadedCore\Request\Part,Core\Request::bodyStream(), or a list or loop ofbytespieces. A file is read from its first byte.$atstringdefault ""A JSON Pointer to the array to read, such as/items. The default is'', which is the whole document.
Options
linesbooloptionalWhentrue, the source is JSON Lines: one JSON value on each line. Thenatmust be''. The default isfalse.maxDepthuintoptionalThe deepest nesting allowed in the document. The default is512, and the largest value is1024.
Return value
Returns Core\Json\Elements<T>. The elements, one at a time. Each element is a new T. When T is mixed, each element is read as decode reads a document. Nothing is read until the loop starts.
Errors
ParseErrorThe JSON is not valid, nests deeper thanmaxDepth, or an element does not matchT. It is also thrown whenatdoes not name an array. The error is thrown when the loop reaches the problem. Your loop has already received the elements before it. The message gives the byte offset.LogicErroratis not a valid JSON Pointer, ormaxDepthis0or above1024. It is also thrown whenlinesistrueandatis not''.RuntimeErrorThe file is closed, or reading from the source fails.
Changelog
| Version | Change |
|---|---|
0.0.6 | Some decoders take a type, such as Core\Json::decodeAs and Core\Request::jsonAs. They check every class inside a shape or an array of that type, at any depth. Core\Request::jsonAs, queryParametersAs and formFieldsAs give the error E0810 when such a class has a plain string property. |
Examples
Import a list from a request body
<?nvs// Shows how to read a large list from a request body one item at a time.
#[Core\Json\Derive]class Product{ public tainted string $sku; public int $stock;
public function constructor(tainted string $sku, int $stock) { $this->sku = $sku; $this->stock = $stock; }}
int $count = 0;int $stock = 0;
// The body is read in pieces, as it arrives. `'/items'` is the path of the array// inside the document. Each element of that array is checked as a `Product`.foreach (Core\Json::decodeEach<Product>(Core\Request::bodyStream(), '/items') as Product $product) { echo $product->sku, ': ', $product->stock, "\n"; $count = $count + 1; $stock = $stock + $product->stock;}
// This prints `3 products, 42 in stock`.echo $count, ' products, ', $stock, " in stock\n";MUG-01: 12CUP-07: 30LID-02: 03 products, 42 in stockRead a json lines log
<?nvs// Shows how to read a JSON Lines log file, where each line is one JSON object.
// The program writes a small log first, so that it has one to read.string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'app.jsonl');Core\IO::write( $path, "{\"level\":\"info\",\"message\":\"server started\"}\n" . "{\"level\":\"error\",\"message\":\"disk is full\"}\n" . "{\"level\":\"info\",\"message\":\"request done\"}\n" . "{\"level\":\"error\",\"message\":\"mail server timed out\"}\n",);
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Read);
// `{ lines: true }` reads one JSON value from each line. The second argument// must be `''`, because there is no array to point into.var $entries = Core\Json::decodeEach<{ level: string, message: string }>($file, '', { lines: true });
int $errors = 0;foreach ($entries as { level: string, message: string } $entry) { if ($entry->level == 'error') { echo $entry->message, "\n"; $errors = $errors + 1; }}
$file->close();
// This prints `2 errors`.echo $errors, " errors\n";disk is fullmail server timed out2 errorsImport a file into a database or nothing
<?nvs// Shows an import that saves every customer of a file, or none of them when the file is broken.
// The third customer in this file is cut off, so the file is not valid JSON.string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'customers.json');Core\IO::write( $path, "[{\"id\":1,\"name\":\"Ada\"},{\"id\":2,\"name\":\"Ben\"},{\"id\":3,\"na",);
// `: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 customers (id integer primary key, name text not null)', []);
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Read);try { // Each customer is added as soon as it is read. The loop gets the first two // customers before the broken part of the file is read. $db->runTransaction(fn(Core\Db\Transaction $tx): void => { foreach (Core\Json::decodeEach<{ id: int, name: string }>($file) as { id: int, name: string } $customer) { $tx->execute('insert into customers (id, name) values (?, ?)', [$customer->id, $customer->name]); echo 'added ', $customer->name, "\n"; } });} catch (ParseError $error) { // The message gives the byte where the file stops being valid JSON. echo $error->message, "\n";}$file->close();
// The error ended the transaction, so both added rows were undone. This prints `0 customers`.echo $db->query('select count(*) as n from customers', [])->all()[0]->int('n') ?? 0, " customers\n";
$db->close();added Adaadded BenCore\Json::decodeEach(): EOF while parsing a string at line 1 column 56, at byte 550 customers