Jan 29, 2026
## Chapter 11: Working with JSON - The Universal Language of APIs
**JSON is like a universal translator - every programming language understands it!**
**Think of JSON as a postcard that can travel anywhere in the world and be understood by everyone!**
### What is JSON?
JSON (JavaScript Object Notation) is a lightweight way to store and transport data. It's like a standardized package that every system can open and read.
**JSON looks like this:**
```json
{
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"hobbies": ["reading", "gaming", "cooking"]
}
```
### Converting PHP to JSON - Packing Your Suitcase
**When you want to send PHP data to JavaScript, APIs, or databases, you pack it into JSON!**
```php
<?php
// Your PHP data
$user = [
"name" => "Meera Sharma",
"age" => 21,
"city" => "Mumbai",
"skills" => ["PHP", "JavaScript", "MySQL"],
"isStudent" => true
];
// Pack it into JSON
$jsonData = json_encode($user);
echo $jsonData;
// Output: {"name":"Meera Sharma","age":21,"city":"Mumbai","skills":["PHP","JavaScript","MySQL"],"isStudent":true}
?>
```
**Pretty JSON for humans to read:**
```php
<?php
$jsonPretty = json_encode($user, JSON_PRETTY_PRINT);
echo $jsonPretty;
?>
```
### Converting JSON to PHP - Unpacking Your Suitcase
**When you receive JSON from APIs or databases, you unpack it back to PHP!**
```php
<?php
// JSON data (maybe from an API)
$jsonString = '{"name":"Meera Sharma","age":21,"city":"Mumbai"}';
// Unpack it to PHP
$userData = json_decode($jsonString, true);
// Now use it like normal PHP
echo "Name: " . $userData["name"] . "n";
echo "Age: " . $userData["age"] . "n";
echo "City: " . $userData["city"] . "n";
?>
```
**The `true` parameter is important - it tells PHP to give you an array instead of an object!**
### Real-World JSON Examples
**Example 1: Saving user preferences to a file**
```php
<?php
// User changes their preferences
$userPreferences = [
"theme" => "dark",
"language" => "en",
"notifications" => true,
"fontSize" => 14
];
// Save to file
file_put_contents('preferences.json', json_encode($userPreferences, JSON_PRETTY_PRINT));
// Later, load them back
$loadedPrefs = json_decode(file_get_contents('preferences.json'), true);
echo "Theme: " . $loadedPrefs["theme"] . "n";
?>
```
**Example 2: API Response Handler**
```php
<?php
// Simulate getting data from an API
function getWeatherData(string $city): array {
// In real life, this would be: file_get_contents("https://api.weather.com/...")
$mockResponse = '{
"city": "' . $city . '",
"temperature": 25,
"condition": "sunny",
"humidity": 65
}';
return json_decode($mockResponse, true);
}
$weather = getWeatherData("Mumbai");
echo "Weather in {$weather["city"]}: {$weather["temperature"]}°C, {$weather["condition"]}n";
?>
```
### Common JSON Mistakes
| Mistake | What Happens | How to Fix |
|---------|---------------|------------|
| Forgetting `true` in json_decode | Get object instead of array | Always use `json_decode($json, true)` |
| Invalid JSON string | json_decode returns null | Check json_last_error() |
| Echoing JSON directly | Shows as plain text | Use header('Content-Type: application/json') |
| Not handling UTF-8 | Garbled characters | Use JSON_UNESCAPED_UNICODE flag |
**Checking for JSON errors:**
```php
<?php
$badJson = '{"name": "John", "age":}'; // Invalid JSON
$result = json_decode($badJson, true);
if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg() . "n";
}
?>
```
### JSON Practice Exercises
1. **User Profile Manager**: Create, save, and load user profiles as JSON
2. **Settings Storage**: Save application settings to JSON file
3. **API Response Parser**: Parse different types of API responses
4. **Data Converter**: Convert between PHP arrays and JSON
5. **Error Logger**: Log errors as JSON with timestamps and details
---