Core\Request::jsonAs
Core\Request::jsonAs<T>({maxDepth?: uint}): TCore\Request::jsonAs<T>( {maxDepth?: uint}, ): T
Reads the body of the request as one JSON object and returns a new instance of one of your classes. You write the class between < and >: Core\Request::jsonAs<NewUser>(). The class needs the #[Core\Json\Derive] attribute, and each public property reads the key with the same name. Write array<NewUser> to read a JSON array that has one object for each element. The body comes from the client, so every string property must be tainted string. A tainted string is text that came from outside your program. This also applies to a class inside a shape or an array, however deep it is.
If the body is not valid JSON, or a field is missing or has the wrong type, jsonAs throws a ParseError. Its issues list has one entry for each wrong field. A web program usually answers that with the status 422. The Content-Type header is not checked.
Every call creates new objects, so two parts of your program never share one.
The examples below read one user, answer a body with wrong fields, and import a list of products.
Options
maxDepthuintoptionalHow deep the document may nest. The default is 512, and the value must be from 1 to 1024. A document with no array or object in it has depth 1.
Return value
Returns T. A new T with its properties read from the body, or one T for each element for an array<T>. Every call creates new objects, so two callers never get the same object.
Errors
LogicErrorThe program is not handling a request. OrbodyStreamorfilesalready read the body, and those two do not keep it. OrThas no#[Core\Json\Derive]attribute. OrmaxDepthis not from 1 to 1024.ParseErrorThe body is not one whole JSON object, or it nests deeper thanmaxDepth. An empty body throws this error too. It is also thrown when a field is missing or has the wrong type. Theissueslist has one entry for each wrong field. TheContent-Typeheader is not checked.RecursionErrorThe call stack is full when a constructor runs. This happens when the call starts with the stack almost full, or when a constructor recurses deeply. A deep body withinmaxDepthdoes not throw this error.RuntimeErrorThe body is larger than[limits] request_body. The bytes past that limit are never stored.IOErrorThe connection failed while the body arrived, or the client sent fewer bytes than itsContent-Lengthsaid.
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
Reading a json body into a class
<?nvs// Shows how to read the JSON body of a request straight into an instance of your own class.
// `#[Core\Json\Derive]` gives the class a JSON format. Each public property is one key.// The body comes from the client, so a string property must be `tainted string`.#[Core\Json\Derive]class NewUser{ public tainted string $name; public int $age;
public function constructor(tainted string $name, int $age) { $this->name = $name; $this->age = $age; }}
// The class between `<` and `>` is the class to create. The result is a `NewUser`.var $user = Core\Request::jsonAs<NewUser>();
// This prints "Ada is 36".echo $user->name, ' is ', $user->age, "\n";Ada is 36A body with wrong fields
<?nvs// Shows how to answer a client whose JSON body does not match your class.
#[Core\Json\Derive]class NewUser{ public tainted string $name; public int $age;
public function constructor(tainted string $name, int $age) { $this->name = $name; $this->age = $age; }}
// The body has no `name`, and its `age` is a string. `Core\Request::jsonAs` throws// one `ParseError`. Its `issues` list has one entry for each wrong field.try { var $user = Core\Request::jsonAs<NewUser>(); echo "201: created\n";} catch (ParseError $error) { // This prints "422: 2 wrong fields", and then the path of each field. echo '422: ', Core\Arr::count($error->issues), " wrong fields\n"; foreach ($error->issues as { path: string, message: string } $issue) { echo ' ', $issue->path, "\n"; }}422: 2 wrong fields name ageImporting a list of products
<?nvs// Shows an API that receives a list of products as JSON and checks each price.
#[Core\Json\Derive]class Product{ public tainted string $sku; public int $cents;
public function constructor(tainted string $sku, int $cents) { $this->sku = $sku; $this->cents = $cents; }}
// The body is a JSON array. `array<Product>` gives one `Product` for each element.var $products = Core\Request::jsonAs<array<Product>>();
uint $imported = 0;foreach ($products as Product $product) { if ($product->cents <= 0) { echo 'refused: ', $product->sku, "\n"; } else { $imported = $imported + 1; }}
// This prints "refused: MUG-02" and then "2 of 3 products imported".echo $imported, ' of ', Core\Arr::count($products), " products imported\n";refused: MUG-022 of 3 products imported