Working with JSON in PHP: Parsing and Serialization in Practice
JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the standard for web APIs and configuration files. In PHP, working with JSON is implemented natively and does not require installing additional extensions. In this article, we will explore how to perform JSON parsing and serialization in PHP with real examples, as well as learn how to handle errors and work with nested structures.
What is JSON Serialization and Parsing?
Before diving into the code, let's define the key concepts:
- Serialization — converting a PHP variable (array, object) into a JSON string.
- Parsing (deserialization) — the reverse process: converting a JSON string into a PHP variable.
PHP provides two main functions for these tasks: json_encode() and json_decode(). Let's look at them in detail.
Serializing Data to JSON with json_encode()
The json_encode() function takes a PHP value (except resources) and returns its JSON representation. Consider a basic example:
<?php$user = [ 'name' => 'Ivan Petrov', 'age' => 28, 'email' => 'ivan@example.com', 'is_active' => true];
$json = json_encode($user);echo $json;// Output: {"name":"Ivan Petrov","age":28,"email":"ivan@example.com","is_active":true}?>By default, json_encode() converts associative arrays into JSON objects. If you need an array, use the JSON_FORCE_OBJECT flag:
<?php$numbers = [10, 20, 30];echo json_encode($numbers); // [10,20,30]echo json_encode($numbers, JSON_FORCE_OBJECT); // {"0":10,"1":20,"2":30}?>Useful json_encode() Flags
JSON_PRETTY_PRINT— formats the output with indentation for readability.JSON_UNESCAPED_UNICODE— does not escape Unicode characters (e.g., Cyrillic letters).JSON_NUMERIC_CHECK— converts strings containing numbers into numeric types.
<?php$data = ['product' => 'Book', 'price' => '1500'];
// Pretty output with Cyrillic charactersecho json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);/*{ "product": "Book", "price": "1500"}*/
// Automatic conversion of string '1500' to a numberecho json_encode($data, JSON_NUMERIC_CHECK);// {"product":"Book","price":1500}?>Parsing JSON in PHP with json_decode()
The json_decode() function takes a JSON string and converts it into a PHP variable. The second parameter $associative determines whether to return an associative array (true) or an object (false, default).
<?php$jsonString = '{"name":"Maria","age":25,"hobbies":["reading","traveling"]}';
// Parsing into an object$obj = json_decode($jsonString);echo $obj->name; // Mariaecho $obj->hobbies[0]; // reading
// Parsing into an associative array$arr = json_decode($jsonString, true);echo $arr['age']; // 25?>Working with Nested Structures
JSON often contains nested objects and arrays. Consider an example with a weather API:
<?php$weatherJson = '{ "city": "Moscow", "temperature": { "current": -5, "feels_like": -8 }, "forecast": [ {"day": "Mon", "temp": -3}, {"day": "Tue", "temp": -1} ]}';
$weather = json_decode($weatherJson, true);
echo "Current temperature: " . $weather['temperature']['current'] . "°C";echo "Feels like: " . $weather['temperature']['feels_like'] . "°C";
foreach ($weather['forecast'] as $day) { echo "{$day['day']}: {$day['temp']}°C";}?>Blogs
Book Recommendations
Read also
What is Python and Why You Should Learn It in 2024