Core\Json\Pieces
The text of a JSON document in pieces of bytes, written one at a time while a foreach loop runs. The whole document is never in memory at once. The text is escaped as Core\Json::encode escapes it, so it is safe inside an HTML page. The pieces are tainted bytes when an item can contain tainted text.
Core\Json\Pieces contains the JSON text of a list, in pieces. Core\Json::encodeEach returns it. It takes an array or an iterable, such as the rows of a database query. The class has no methods. You read it with a foreach loop.
Each item is bytes, at most 64 KiB long. The [, the commas and the ] are part of the pieces. With { lines: true }, the text is JSON Lines: one value on each line, with no brackets. Use $piece as string when you need the text of a piece.
The pieces are tainted bytes when an item can contain tainted text, such as a value read from a request. Core\Json::encode returns a tainted string for the same items. Core\Response::startStream sends only pieces that are not tainted.
Nothing is encoded until the loop starts. The method takes the next item only when it needs it, so the whole document is never in memory at once. You can read the pieces only once. After the last piece, a loop gives no items.
The loop throws a LogicError when an item cannot be written as JSON, as Core\Json::encode does. An object whose class does not have #[Core\Json\Derive] is one example. Your loop may already have received some pieces before the error. To send the pieces as a response, pass each one to the write method of Core\Response::startStream. To write them to a file, pass them to Core\IO::writeStream.
<?nvsarray<{ id: int, name: string }> $users = [ { id: 1, name: 'Ada' }, { id: 2, name: 'Ben' },];
// A short list fits in one piece.foreach (Core\Json::encodeEach($users) as var $piece) { echo $piece as string, "\n";}
// `writeStream` writes the pieces to a file. This file has one user on each line.string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'users.jsonl');Core\IO::writeStream($path, Core\Json::encodeEach($users, { lines: true }), { overwrite: true });echo Core\IO::read($path);[{"id":1,"name":"Ada"},{"id":2,"name":"Ben"}]{"id":1,"name":"Ada"}{"id":2,"name":"Ben"}Returned by
You get a Core\Json\Pieces from these methods:
Example apps
These complete apps use this class. You can download and run each one.
- Chat: A chat app with rooms, WebSockets and SQLite. One Novis server sends the pages and runs every connection, with no separate WebSocket server and no library.
