typestar

JSON in PHP

Serializing to JSON and back with the built-in functions.

<?php
$payload = ["name" => "typestar", "langs" => ["php", "go"], "stars" => 3];

$text = json_encode($payload);
echo $text, "\n";

// true asks for assoc arrays instead of stdClass objects
$parsed = json_decode($text, true);
echo $parsed["name"], "\n";
echo count($parsed["langs"]), "\n";

echo json_encode(["stars" => $parsed["stars"]], JSON_PRETTY_PRINT), "\n";

// throw on malformed input instead of returning null
try {
    json_decode("{oops", flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "bad json: ", $e->getMessage(), "\n";
}

How it works

  1. json_encode turns an array into a compact string.
  2. json_decode with true returns assoc arrays, not stdClass.
  3. JSON_PRETTY_PRINT formats output for human eyes.
  4. JSON_THROW_ON_ERROR raises JsonException on malformed input.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
549
Tokens
131
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 105 seconds.

Type this snippet

Step 2 of 3 in Modern touches, step 23 of 27 in Language basics.

← Previous Next →

JSON in other languages