iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP JSON

PHP has two functions that cover most JSON needs — json_encode and json_decode. Both ship with the standard library.

Encode

PHP
$user = ['name' => 'Ada', 'roles' => ['admin', 'dev']];

echo json_encode($user);
// {"name":"Ada","roles":["admin","dev"]}

echo json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

Decode

PHP
$json = '{"name":"Ada","age":36}';

$obj = json_decode($json);            // -> stdClass object
$arr = json_decode($json, true);      // -> associative array

echo $obj->name;     // Ada
echo $arr['name'];   // Ada

Useful flags

FlagEffect
JSON_PRETTY_PRINTIndented output.
JSON_UNESCAPED_SLASHESDon't escape /.
JSON_UNESCAPED_UNICODEKeep emoji and Unicode literal.
JSON_THROW_ON_ERRORThrow JsonException instead of returning false.
JSON_FORCE_OBJECTEmit {} for empty arrays instead of [].
JSON_NUMERIC_CHECKNumeric strings encoded as numbers.

Error handling

PHP
try {
    $data = json_decode($input, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo 'Bad JSON: ', $e->getMessage();
}

Custom objects with JsonSerializable

PHP
class User implements JsonSerializable {
    public function __construct(public string $name, private string $secret) {}

    public function jsonSerialize(): array {
        return ['name' => $this->name];   // skip the secret
    }
}

echo json_encode(new User('Ada', 'shh'));   // {"name":"Ada"}
Tip: Default to $assoc = true when decoding into something you'll iterate. The stdClass shape forces awkward -> access for what's really a hash map.

Example

Example
<?php
$user = ['name' => 'Ada', 'roles' => ['admin', 'dev']];
$json = json_encode($user, JSON_PRETTY_PRINT);
echo $json, PHP_EOL;
print_r(json_decode($json, true));
Try it Yourself »

Exercise

Encode a value to JSON.

($user);

Test yourself

Q1. Encode with…
Q2. For exceptions on bad JSON pass…
Q3. Empty PHP array encodes to…

Discussion

Loading…