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
json_encodeturns an array into a compact string.json_decodewithtruereturns assoc arrays, notstdClass.JSON_PRETTY_PRINTformats output for human eyes.JSON_THROW_ON_ERRORraisesJsonExceptionon malformed input.
Keywords and builtins used here
catchcountechojson_decodejson_encodetruetry
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.
Step 2 of 3 in Modern touches, step 23 of 27 in Language basics.