Skip to main content
RESTful Principles
CHAPTER 09 Beginner

Working with JSON Data

Updated: May 13, 2026
5 min read

# CHAPTER 9

Working with JSON Data

1. Introduction

JSON (JavaScript Object Notation) is the undisputed king of data formats in modern web APIs. It has effectively replaced XML because it is lighter, faster to parse, and incredibly easy for humans to read. In Chapter 9, we will learn the strict syntax rules of JSON, the difference between objects and arrays, and how to seamlessly convert JSON strings into usable PHP arrays (and vice versa).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Write valid JSON following strict syntax rules.
  • Differentiate between JSON Objects and JSON Arrays.
  • Convert PHP arrays into JSON strings using jsonencode().
  • Convert JSON strings into PHP arrays using jsondecode().
  • Handle JSON encoding/decoding errors in PHP.

3. Beginner-Friendly Explanation

JSON is simply a way to write data down as plain text so it can be sent over a wire. Imagine you want to mail a physical table. You can't fit a table in a mailbox. So, you break the table down into pieces, put it in a flat box with instructions (this is like converting data to JSON). The person receives the box, reads the instructions, and builds the table back into its original 3D form (this is parsing JSON back into code).

4. Real-World Examples

  • Configuration Files: Many modern software tools (like VS Code or Node.js package.json) use JSON to save user settings.
  • NoSQL Databases: Databases like MongoDB store data natively in a format that is nearly identical to JSON, making APIs very fast to build.

5. Detailed Code Examples

In PHP, working with JSON revolves around two functions: jsonencode (Array to Text) and jsondecode (Text to Array/Object).

Encoding (PHP to JSON):

php
12345678910111213
<?php
// A standard PHP Associative Array
$user = [
    "id" => 1,
    "name" => "Alice",
    "is_active" => true,
    "skills" => ["PHP", "MySQL"]
];

// Convert to JSON String
$jsonString = json_encode($user);
echo $jsonString;
?>

Decoding (JSON to PHP):

php
12345678
<?php
$jsonInput = &#039;{"name":"Bob","age":30}';

// Convert JSON String to PHP Associative Array (Notice the 'true' parameter)
$phpArray = json_decode($jsonInput, true);

echo "Hello, " . $phpArray[&#039;name']; // Outputs: Hello, Bob
?>

6. Request/Response Examples

When building an API, reading the incoming JSON from a client requires a specific approach in PHP.

Reading an incoming POST request:

php
12345678910111213141516
<?php
// 1. Read the raw text from the request body
$rawJsonText = file_get_contents("php://input");

// 2. Decode the text into a PHP array
$data = json_decode($rawJsonText, true);

// 3. Check for JSON syntax errors
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid JSON format provided."]);
    exit;
}

echo "Received name: " . $data[&#039;name'];
?>

7. HTTP Examples

When your API returns JSON, you must format the response cleanly.
http
1234567891011
HTTP/1.1 200 OK
Content-Type: application/json

{
  "product": "Mechanical Keyboard",
  "stock": 45,
  "features": {
    "wireless": true,
    "rgb": true
  }
}

8. JSON Examples

JSON syntax is very strict. It relies on Objects {} (Key-Value pairs) and Arrays [] (Lists).

Valid JSON:

json
1234567
{
  "title": "API Guide",
  "page_count": 120,
  "is_published": true,
  "authors": ["Sam", "Alex"],
  "meta": null
}

9. Best Practices

  • Always use double quotes: In JSON, keys and string values *must* be wrapped in double quotes ". Single quotes ' will cause a fatal parsing error.
  • No trailing commas: The last item in a JSON object or array cannot have a comma after it.
  • Handle decoding errors: Never trust that the client sent valid JSON. Always check jsonlasterror() to ensure the string was successfully parsed before trying to use the data.

10. Common Mistakes

  • Forgetting the 'true' parameter: In PHP, jsondecode($json) returns a PHP Object. jsondecode($json, true) returns a PHP Associative Array. Beginners often forget the true and get confused when they can't access data using $data['key'].
  • Accidental HTML: If you have any HTML outside of your <?php ?> tags (even a blank space before the tag), PHP will output it alongside your JSON, breaking the JSON format completely.

11. Mini Exercises

  1. 1. Look at this JSON string. Spot the syntax error: { 'name': 'John', 'age': 25, }
*(Answer: Single quotes are not allowed, and there is a trailing comma after 25).*

12. Coding Challenges

Challenge 1: Create a PHP script with a multidimensional array containing a list of 3 users (each with an id and name). Use jsonencode to turn it into a JSON string, and output it with the proper application/json Content-Type header.

13. MCQs with Answers

Question 1

Which of the following is VALID JSON?

Question 2

Which PHP function converts a JSON string into a PHP array?

Question 3

How do you read a raw JSON payload sent to a PHP server via POST?

14. Interview Questions

  • Q: Explain the strict syntax rules of JSON compared to a standard JavaScript object.
  • Q: What is the difference between jsondecode($str) and jsondecode($str, true) in PHP?
  • Q: Why did JSON replace XML as the standard data format for web APIs?

15. FAQs

Q: Can JSON store functions or methods? A: No. JSON is strictly a data serialization format. It can only store strings, numbers, booleans, null, arrays, and objects. It cannot store logic, functions, or dates (dates must be stored as strings).

Q: How do I make my JSON look pretty and indented when I output it? A: In PHP, you can use a special flag: jsonencode($data, JSONPRETTYPRINT). This adds spaces and line breaks to make it readable in a browser.

16. Summary

In Chapter 9, we mastered JSON data. We learned that while JSON is simple, it is highly strict regarding double quotes and commas. We covered the essential PHP functions jsonencode() and jsondecode(), and emphasized the importance of using filegetcontents("php://input") to capture incoming API data.

17. Next Chapter Recommendation

We now know how to format data and use HTTP methods. But how do we structure our URLs when our database relationships become complex? Proceed to Chapter 10: REST URL Design Best Practices to master hierarchical routing.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·