JSON Encoding and Decoding
Convert PHP arrays to JSON and parse JSON responses with json_encode/json_decode.
JSON Encoding and Decoding is a free PHP Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format used for API communication and config files. PHP has built-in functions for encoding and decoding it.
json_encode()
Converts a PHP value (array, object, scalar) to a JSON string.
<?php
$data = ["name" => "Alice", "age" => 30, "active" => true];
$json = json_encode($data);
echo $json; // {"name":"Alice","age":30,"active":true}json_decode()
Parses a JSON string and returns a PHP value. By default returns stdClass objects; pass true as the second argument for associative arrays.
<?php
$json = '{"name":"Alice","age":30}';
$obj = json_decode($json); // stdClass
$arr = json_decode($json, true); // associative array
echo $arr["name"]; // "Alice"Pretty-Printing JSON
Use JSON_PRETTY_PRINT flag to format output for human readability.
<?php
$json = json_encode(["a" => 1, "b" => 2], JSON_PRETTY_PRINT);
echo $json;
// {
// "a": 1,
// "b": 2
// }Useful json_encode Flags
Common flags: JSON_UNESCAPED_UNICODE (keep UTF-8 as-is), JSON_UNESCAPED_SLASHES (no backslash before /), JSON_THROW_ON_ERROR (throws on failure).
<?php
$json = json_encode(["url" => "https://example.com/path"],
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);Error Handling
Check json_last_error() after encoding/decoding, or use JSON_THROW_ON_ERROR to get an exception automatically.
<?php
try {
$data = json_decode($input, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
echo "Invalid JSON: ".$e->getMessage();
}Encoding Objects
Objects are encoded as JSON objects. Only public properties are included by default. Implement JsonSerializable to control serialization.
<?php
class Point implements \JsonSerializable {
public function __construct(
private float $x, private float $y
) {}
public function jsonSerialize(): mixed {
return ["x" => $this->x, "y" => $this->y];
}
}
echo json_encode(new Point(1.0, 2.5)); // {"x":1,"y":2.5}Nested Structures
JSON supports nesting. Deeply nested PHP arrays encode to nested JSON objects/arrays seamlessly.
<?php
$order = [
"id" => 1,
"items" => [
["sku" => "A1", "qty" => 2],
["sku" => "B3", "qty" => 1],
],
];
echo json_encode($order, JSON_PRETTY_PRINT);Decoding Depth
The 3rd parameter of json_decode sets maximum recursion depth (default 512). Very deep JSON may need a higher limit.
JSON_NUMERIC_CHECK
The JSON_NUMERIC_CHECK flag converts numeric strings to numbers during encoding. Use with care — it may break phone numbers.
Streaming Large JSON
For very large JSON files, use a streaming parser library (e.g. halaxa/json-machine) instead of loading the entire file with json_decode.
Summary
json_encode converts PHP values to JSON strings. json_decode parses JSON. Use JSON_THROW_ON_ERROR for safe error handling.
Quick Check
How do you get an associative array from json_decode?
Frequently asked questions
Is the “JSON Encoding and Decoding” lesson free?
Yes — the full text of “JSON Encoding and Decoding” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “JSON Encoding and Decoding”?
Convert PHP arrays to JSON and parse JSON responses with json_encode/json_decode. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “JSON Encoding and Decoding” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- JSON Encoding and Decoding
- Making HTTP Requests with cURL
- Handling API Responses and Errors
- Building a Simple API Client