JSON Handling in PHP

7 questions found

How do you convert a PHP array or object into a JSON formatted string using json_encode?

Beginner
The json_encode function converts a PHP array or object into a JSON formatted string, which is the standard, widely used data format for exchanging information between different systems, such as sending a response from a PHP API to a JavaScript based frontend, and it automatically handles converting PHP's native data types, like arrays, strings, and booleans, into their correct corresponding JSON representations.
$data = ['name' => 'Ali', 'age' => 30];
echo json_encode($data);
Real-world example An API endpoint uses json_encode to convert an array of product data retrieved from the database into a JSON response, which the frontend JavaScript application then parses to display the products on the page.

Common follow-ups: How do you make json_encode produce nicely formatted, indented output?;What happens if the array you are encoding contains a resource type that cannot be represented in JSON?

RESTful API Development with PHP;Arrays in PHP

How do you convert a JSON formatted string back into a PHP array or object using json_decode?

Beginner
The json_decode function parses a JSON formatted string and converts it back into a corresponding PHP value, returning a PHP object by default, or an associative array if you pass true as the second argument, letting you easily work with JSON data received from an external API or submitted in a request body using familiar PHP array or object syntax.
$json = '{"name": "Ali", "age": 30}';
$data = json_decode($json, true);
echo $data['name'];
Real-world example An application receiving a webhook notification from a third party payment provider uses json_decode to parse the incoming JSON payload into a PHP array, immediately making the payment details easily accessible for further processing.

Common follow-ups: What is the difference between decoding JSON as an object versus as an associative array?;What does json_decode return if the input string is not valid JSON?

RESTful API Development with PHP;Error & Exception Handling

How do you properly handle errors when parsing potentially invalid JSON, and how does the JSON_THROW_ON_ERROR flag simplify this compared to manually checking json_last_error?

Intermediate
By default, json_decode returns null if it encounters invalid JSON, but null is also a valid JSON value itself, making it ambiguous whether decoding actually failed or the JSON genuinely contained a null value, which historically required manually checking json_last_error afterward, while passing the JSON_THROW_ON_ERROR flag instead causes json_decode to throw a proper catchable JsonException on failure, letting you handle invalid JSON using a standard try catch block instead of manually checking an error code after every single call.
try {
    $data = json_decode($jsonString, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo 'Invalid JSON received: ' . $e->getMessage();
}
Real-world example An API integration script switches from manually checking json_last_error after every decode call to using the JSON_THROW_ON_ERROR flag, significantly simplifying its error handling code with a single consistent try catch block.

Common follow-ups: What specific error codes can json_last_error return besides indicating success?;Is JSON_THROW_ON_ERROR available in older PHP versions?

Error & Exception Handling;RESTful API Development with PHP

How do you control the depth and formatting of json_encode output, such as pretty printing JSON for readability or handling deeply nested data structures?

Intermediate
The json_encode function accepts an optional flags parameter that lets you control formatting behavior, such as JSON_PRETTY_PRINT to produce nicely indented, human readable output useful for debugging or configuration files, and it also accepts a depth parameter controlling how deeply nested arrays or objects it will process before throwing an error, which is a useful safeguard against accidentally encoding an extremely deep or circular data structure.
$data = ['user' => ['name' => 'Ali', 'roles' => ['admin', 'editor']]];
echo json_encode($data, JSON_PRETTY_PRINT);
Real-world example A configuration management tool uses JSON_PRETTY_PRINT when writing a configuration file to disk, ensuring the resulting file remains easy for a human developer to read and manually edit if ever needed.

Common follow-ups: What other useful flags does json_encode support besides JSON_PRETTY_PRINT?;What happens if you try to encode a PHP array containing a circular reference?

File Handling & File System Functions;Deployment & Hosting for PHP Applications

How can PHP objects implementing the JsonSerializable interface customize exactly how they are converted into JSON when passed to json_encode?

Intermediate
The JsonSerializable interface requires implementing a single method, jsonSerialize, which returns the exact data structure that should actually be used when json_encode processes an instance of that class, letting you control precisely what gets included in the resulting JSON, such as excluding a sensitive password property or renaming certain fields, rather than json_encode simply dumping every public property of the object by default.
class User implements JsonSerializable {
    public function __construct(private string $name, private string $password) {}
    public function jsonSerialize(): mixed {
        return ['name' => $this->name];
    }
}
echo json_encode(new User('Ali', 'secret123'));
Real-world example A User class implements JsonSerializable to explicitly exclude the password property from ever appearing in JSON output, providing a strong guarantee against accidentally leaking sensitive data through an API response regardless of how that object gets encoded.

Common follow-ups: What happens to a class's private and protected properties when json_encode processes it without JsonSerializable implemented?;How does this interface compare to using a dedicated data transfer object specifically for API responses?

OOP;Security

How should an API validate the structure and types of incoming JSON data to ensure it matches the expected schema before processing it further?

Advanced
After successfully parsing incoming JSON into a PHP array or object, an API should still validate that the resulting data actually contains all required fields with the expected types and acceptable values, since successfully parsed JSON does not guarantee the data is structurally or semantically valid for your application's needs, and this is commonly handled either through manual validation logic or by using a dedicated JSON schema validation library that can systematically check an entire structure against a formally defined schema.
$data = json_decode($jsonString, true, flags: JSON_THROW_ON_ERROR);
if (!isset($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
    throw new ValidationException('Invalid or missing email field');
}
Real-world example An API endpoint successfully parses an incoming JSON request body but still explicitly validates that a required email field is present and properly formatted before proceeding, since the JSON being syntactically valid says nothing about whether it actually contains the data the endpoint genuinely needs.

Common follow-ups: What is a JSON schema and how does formally defining one help automate this kind of validation?;How does this JSON structure validation relate to the general form validation concepts discussed elsewhere?

Form Handling & Validation;RESTful API Development with PHP

What performance considerations arise when working with very large JSON payloads in PHP, and how do streaming JSON parsers help address them?

Advanced
Since json_decode must parse an entire JSON string into memory all at once, processing extremely large JSON payloads, such as a multi hundred megabyte data export, can consume a significant amount of memory and potentially exceed PHP's configured memory limit, and for these cases, a streaming JSON parser processes the input incrementally, emitting individual pieces of data as they are encountered, rather than requiring the entire structure to be fully loaded into memory before any processing can begin.
// Conceptual streaming approach using a library like JsonMachine
foreach (\JsonMachine\Items::fromFile('large-export.json') as $key => $item) {
    processItem($item);
}
Real-world example A data import tool switches from json_decode to a streaming JSON parsing library after repeatedly hitting PHP's memory limit while trying to fully parse an enormous exported data file all at once, instead processing each record incrementally as it streams through the file.

Common follow-ups: What third party libraries provide streaming JSON parsing capabilities in PHP?;How does this approach compare in complexity to simply increasing PHP's memory limit configuration?

Performance Optimization & OPcache;File Handling & File System Functions