bhylu.com

Advertisements

PHP JSON

JSON transfers structured values, but decoding successfully is only the first boundary. The resulting data still needs the shape and range your operation expects.

How it works

Use JSON_THROW_ON_ERROR to make malformed JSON a visible failure. Associative decoding can give a convenient array representation, while object decoding answers a different shape contract. JSON numbers and strings are distinct; large identifiers and cross-language numeric limits deserve deliberate treatment. Validate required fields before passing decoded values into a typed domain function.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l json.php
php json.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · json.php

<?php
declare(strict_types=1);

$raw = '{"item":"Spade","quantity":2}';
$data = json_decode($raw,true,32,JSON_THROW_ON_ERROR);
if (!is_array($data) || !is_string($data["item"] ?? null) || !is_int($data["quantity"] ?? null) || $data["quantity"] <= 0) throw new InvalidArgumentException("Invalid loan shape");
echo $data["item"], ": ", $data["quantity"], "\n";
echo json_encode(["accepted"=>true],JSON_THROW_ON_ERROR), "\n";

Expected result

Spade: 2
{"accepted":true}

The parser produces an array whose fields are then checked independently. A string quantity would not pass the integer check. Encoding the final response uses the same explicit failure policy. This small example does not reserve stock, authenticate an actor or establish a maximum application payload size.

Check the official PHP manual for detailed version and API contracts.