Core\Http\Response::jsonAs
Decodes the body of a reply as JSON into the type you name, for example a shape or a class.
You write the type between < and >: $response->jsonAs<User>(). The result has that type, so you read its fields with no further checks. Write array<User> when the reply is a JSON array. If the body is not valid JSON, is not UTF-8 text, or does not fit the type, jsonAs throws a ParseError. The message says what did not fit. The option maxDepth limits how deeply the JSON may be nested.
The text comes from another server, so every text field of the type must be tainted.
Good to know: the examples use Core\Test::answerHttp to give fixed replies, so they run without a network. They read one user, show three replies that do not fit, and add up a list of orders from a shop.
Options
maxDepthuintoptionalHow deep the document may nest. A deeper document throws an error. A scalar document is depth 1.
Return value
Returns T. A new T built from the document's fields, or one T per element for an array<T>. Every text property of T must be declared tainted, because another server chose these bytes.
Errors
LogicErrorThas no#[Json\Derive]decoder. OrmaxDepthis outside 1..=1024.ParseErrorThe body is not one complete JSON document within that depth. A reply with no body, or a body that is not UTF-8, also throws this error. Or the document is not the objectTdecodes from, or its fields are missing or have the wrong type. Each failed field is one issue on the error, with its own path. The reply'sContent-Typeheader is not checked.
Examples
Reading a json reply
<?nvs// Shows how to read a JSON reply into a shape with named fields.
// `Core\Test::answerHttp` gives a fixed reply to this address, so the example runs// without a network.Core\Test::answerHttp('https://api.example.com/users/7', 200, { body: "{\"name\":\"Ada\",\"id\":7}", headers: ['Content-Type' => 'application/json'],});
Core\Http\Response $response = Core\Http\Client::get('https://api.example.com/users/7');
// `jsonAs<T>()` decodes the body into the type `T` that you write between `<` and `>`.// The text came from another server, so the shape is `tainted`.var $user = $response->jsonAs<tainted { name: string, id: int }>();
// This prints `Ada has the id 7`.echo $user->name, ' has the id ', $user->id, "\n";Ada has the id 7A reply that is not json
<?nvs// Shows what happens when a reply is not the JSON document the program expects.
// The text in a reply comes from another server, so the text property is `tainted`.#[Core\Json\Derive]class User{ public tainted string $name; public int $id;
public function constructor(tainted string $name, int $id) { $this->name = $name; $this->id = $id; }}
// The first server sends a web page. The second sends JSON without the field `id`.Core\Test::answerHttp('https://api.example.com/page', 200, { body: '<html>Maintenance</html>' });Core\Test::answerHttp('https://api.example.com/partial', 200, { body: "{\"name\":\"Ada\"}" });// The third server sends bytes that are not UTF-8 text.Core\Test::answerHttp('https://api.example.com/blob', 200, { body: Core\Encoding::fromHex('7b22ff227d') });
// `jsonAs<T>()` throws a `ParseError` when the body does not fit the type `T`.// This prints one error message for each of the three replies.array<string> $urls = [ 'https://api.example.com/page', 'https://api.example.com/partial', 'https://api.example.com/blob',];foreach ($urls as string $url) { Core\Http\Response $response = Core\Http\Client::get($url); try { User $user = $response->jsonAs<User>(); echo $user->name, "\n"; } catch (ParseError $error) { echo $error->message, "\n"; }}Core\Http\Response::jsonAs(): expected value at line 1 column 1Core\Http\Response::jsonAs(): 1 value(s) of `User` did not matchCore\Http\Response::jsonAs(): the reply's body is not UTF-8, so it is not a JSON documentReading a list of orders
<?nvs// Shows a program that downloads a list of orders from a shop and adds up their totals.
#[Core\Json\Derive]class Order{ public int $id; public int $cents;
public function constructor(int $id, int $cents) { $this->id = $id; $this->cents = $cents; }}
// A fixed reply, so the example runs without a network. The body is a JSON array.Core\Test::answerHttp('https://shop.example.com/api/orders', 200, { body: "[{\"id\":1,\"cents\":1250},{\"id\":2,\"cents\":899},{\"id\":3,\"cents\":4000}]",});
Core\Http\Response $response = Core\Http\Client::get('https://shop.example.com/api/orders');
// `array<Order>` reads a JSON array, and each element becomes one `Order`.array<Order> $orders = $response->jsonAs<array<Order>>();
int $sum = 0;foreach ($orders as Order $order) { $sum = $sum + $order->cents;}// This prints `3 orders, 6149 cents`.echo Core\Arr::count($orders), ' orders, ', $sum, " cents\n";3 orders, 6149 cents