Skip to content

Chapter 33 of 38

JSON Handling

Encode, decode, validate, report failures, and design stable JSON representations.

32 minutes 10 quick checksBy Subha Prasad
Lesson 33 of 38Course navigation

Lesson content

Read, practise, then check your understanding

PHP JSON functions require valid UTF-8. Use exceptions rather than silently accepting partial or ambiguous failure.

Practical example

<?php
$data = json_decode($body, true, 64, JSON_THROW_ON_ERROR);
if (!is_array($data) || !isset($data['name'])) throw new InvalidArgumentException();
$response = json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);

Decoding syntax does not validate the application schema. Define required keys, types, ranges, unknown-key policy, and maximum depth/body size. Stable APIs should document number/date/null representation and avoid leaking internal object structures.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes json_decode?
Which PHP term matches this description: Conversion from JSON text to PHP values.
Which statement best describes json_encode?
Which PHP term matches this description: Conversion from supported PHP values to JSON text.
Which statement best describes JSON_THROW_ON_ERROR?
Which PHP term matches this description: A flag reporting JSON failures with JsonException.
Which statement best describes associative decode?
Which PHP term matches this description: Decoding JSON objects as PHP arrays instead of stdClass.
Which statement best describes UTF-8?
Which PHP term matches this description: The encoding required for JSON strings handled by PHP JSON functions.

0 of 10 checks passed

Your progress is saved on this device.

JSON Handling | PHP Lesson | Subha Prasad