JSON Encoding and Decoding in PHP Practice Questions with Solutions

Introduction

JSON (JavaScript Object Notation) is a popular format for storing and exchanging data between applications. PHP provides built-in functions to convert PHP data into JSON and JSON data back into PHP variables. In this chapter, you will practise JSON encoding and decoding in PHP through practical examples involving students, employees, products, and company records.

Question 1: Convert a PHP Array into JSON Using json_encode()

Problem Statement

Create a PHP program that stores student details in an array and converts the array into JSON format.

PHP Solution

<?php

$student = [
    "name" => "Rahul",
    "age" => 20,
    "course" => "PHP"
];

$jsonData = json_encode($student);

echo $jsonData;

?>

Sample Output

{"name":"Rahul","age":20,"course":"PHP"}

Explanation

  • $student stores student details in an associative array.
  • json_encode() converts the PHP array into a JSON string.
  • $jsonData stores the converted JSON data.
  • echo displays the JSON string.

Concepts Covered

  • JSON format
  • json_encode()
  • PHP associative arrays
  • JSON strings

Question 2: Convert JSON Data into a PHP Array Using json_decode()

Problem Statement

Create a PHP program that converts JSON student data into a PHP associative array.

PHP Solution

<?php

$jsonData = '{"name":"Amit","age":22,"course":"Python"}';

$student = json_decode($jsonData, true);

echo "Name: " . $student["name"];
echo "\nAge: " . $student["age"];
echo "\nCourse: " . $student["course"];

?>

Sample Output

Name: Amit
Age: 22
Course: Python

Explanation

  • $jsonData contains JSON information.
  • json_decode() converts JSON into a PHP value.
  • The second argument true converts JSON objects into associative arrays.
  • You can access the values using array keys.

Concepts Covered

  • json_decode()
  • JSON decoding
  • Associative arrays
  • Accessing decoded values

Question 3: Convert a PHP Array into a JSON Object

Problem Statement

Create a PHP program that converts employee details into a JSON object.

PHP Solution

<?php

$employee = [
    "id" => 101,
    "name" => "Priya",
    "department" => "HR",
    "salary" => 35000
];

$jsonData = json_encode($employee, JSON_PRETTY_PRINT);

echo $jsonData;

?>

Sample Output

{
    "id": 101,
    "name": "Priya",
    "department": "HR",
    "salary": 35000
}

Explanation

  • The employee array contains four fields.
  • json_encode() converts the array into JSON.
  • JSON_PRETTY_PRINT formats the JSON with indentation and line breaks.
  • This makes JSON easier to read.

Concepts Covered

  • JSON objects
  • JSON_PRETTY_PRINT
  • JSON formatting
  • Employee records

Question 4: Convert JSON Data into a PHP Object

Problem Statement

Create a PHP program that converts JSON product data into a PHP object and accesses its properties.

PHP Solution

<?php

$jsonData = '{"product":"Laptop","price":45000,"brand":"Dell"}';

$product = json_decode($jsonData);

echo "Product: " . $product->product;
echo "\nPrice: " . $product->price;
echo "\nBrand: " . $product->brand;

?>

Sample Output

Product: Laptop
Price: 45000
Brand: Dell

Explanation

  • json_decode() converts JSON into a PHP object by default.
  • The arrow operator -> accesses object properties.
  • $product->product returns the product name.
  • $product->price returns the product price.

Concepts Covered

  • JSON objects
  • PHP objects
  • Object properties
  • Object access operator

Question 5: Convert a Multidimensional PHP Array into JSON

Problem Statement

Create a PHP program that stores multiple student records in a multidimensional array and converts them into JSON.

PHP Solution

<?php

$students = [
    [
        "id" => 1,
        "name" => "Rahul",
        "marks" => 85
    ],
    [
        "id" => 2,
        "name" => "Priya",
        "marks" => 92
    ],
    [
        "id" => 3,
        "name" => "Amit",
        "marks" => 78
    ]
];

$jsonData = json_encode($students, JSON_PRETTY_PRINT);

echo $jsonData;

?>

Sample Output

[
    {
        "id": 1,
        "name": "Rahul",
        "marks": 85
    },
    {
        "id": 2,
        "name": "Priya",
        "marks": 92
    },
    {
        "id": 3,
        "name": "Amit",
        "marks": 78
    }
]

Explanation

  • $students stores multiple student records.
  • Each inner array represents one student.
  • json_encode() converts the complete multidimensional array into JSON.
  • JSON_PRETTY_PRINT makes the output readable.

Concepts Covered

  • Multidimensional arrays
  • JSON arrays
  • json_encode()
  • Multiple records

Question 6: Decode JSON Containing Multiple Records

Problem Statement

Create a PHP program that decodes JSON data containing multiple employee records and displays their names and salaries.

PHP Solution

<?php

$jsonData = '[
    {"name":"Rahul","salary":30000},
    {"name":"Priya","salary":40000},
    {"name":"Amit","salary":35000}
]';

$employees = json_decode($jsonData, true);

foreach ($employees as $employee) {

    echo "Name: " . $employee["name"];
    echo " | Salary: " . $employee["salary"] . "\n";

}

?>

Sample Output

Name: Rahul | Salary: 30000
Name: Priya | Salary: 40000
Name: Amit | Salary: 35000

Explanation

  • $jsonData contains multiple employee records in JSON format.
  • json_decode($jsonData, true) converts the JSON into a PHP array.
  • foreach visits each employee record.
  • Array keys are used to display employee names and salaries.

Concepts Covered

  • JSON decoding
  • Multiple JSON records
  • foreach loop
  • Employee data

Question 7: Encode JSON Without Escaping Unicode Characters

Problem Statement

Create a PHP program that converts student information containing Hindi text into JSON without converting Unicode characters into escape sequences.

PHP Solution

<?php

$student = [
    "name" => "Rahul",
    "city" => "दिल्ली",
    "course" => "PHP"
];

$jsonData = json_encode($student, JSON_UNESCAPED_UNICODE);

echo $jsonData;

?>

Sample Output

{"name":"Rahul","city":"दिल्ली","course":"PHP"}

Explanation

  • The array contains Hindi text.
  • json_encode() normally escapes some Unicode characters.
  • JSON_UNESCAPED_UNICODE keeps Unicode characters readable in the JSON output.
  • This is useful when working with multilingual information.

Concepts Covered

  • Unicode characters
  • JSON_UNESCAPED_UNICODE
  • JSON encoding
  • Multilingual data

Question 8: Check JSON Decoding Errors Using json_last_error()

Problem Statement

Create a PHP program that checks whether a JSON string is valid and displays an appropriate message.

PHP Solution

<?php

$jsonData = '{"name":"Rahul","age":20';

$data = json_decode($jsonData);

if (json_last_error() === JSON_ERROR_NONE) {

    echo "Valid JSON data.";

} else {

    echo "Invalid JSON data.";
    echo "\nError: " . json_last_error_msg();

}

?>

Sample Output

Invalid JSON data.
Error: Syntax error

Explanation

  • The JSON string is missing a closing brace.
  • json_decode() attempts to decode the JSON.
  • json_last_error() returns the most recent JSON error code.
  • JSON_ERROR_NONE means no error occurred.
  • json_last_error_msg() returns a readable error message.

Concepts Covered

  • JSON validation
  • json_last_error()
  • json_last_error_msg()
  • JSON_ERROR_NONE

Question 9: Encode JSON Data with Numeric Values as Strings

Problem Statement

Create a PHP program that converts employee details into JSON and encodes numeric values as strings.

PHP Solution

<?php

$employee = [
    "id" => 101,
    "name" => "Amit",
    "salary" => 35000
];

$jsonData = json_encode($employee, JSON_NUMERIC_CHECK);

echo $jsonData;

?>

Sample Output

{"id":101,"name":"Amit","salary":35000}

Explanation

  • The employee array contains numeric values.
  • JSON_NUMERIC_CHECK converts numeric strings into JSON numbers.
  • In this example, the values are already integers, so the output remains numeric.
  • This flag is especially useful when numeric values are stored as strings.

Concepts Covered

  • JSON_NUMERIC_CHECK
  • Numeric JSON values
  • JSON encoding options

Question 10: Build a Simple Employee JSON Data System

Problem Statement

Create a PHP program that stores employee information in an array, converts it into JSON, decodes the JSON, and displays the employee details.

PHP Solution

<?php

$employee = [
    "id" => 101,
    "name" => "Rahul",
    "department" => "IT",
    "salary" => 40000
];

// Convert PHP array into JSON

$jsonData = json_encode($employee, JSON_PRETTY_PRINT);

echo "JSON Employee Data:\n";
echo $jsonData;

// Convert JSON into PHP array

$employeeData = json_decode($jsonData, true);

echo "\n\nEmployee Details:\n";

echo "ID: " . $employeeData["id"];
echo "\nName: " . $employeeData["name"];
echo "\nDepartment: " . $employeeData["department"];
echo "\nSalary: " . $employeeData["salary"];

?>

Sample Output

JSON Employee Data:
{
    "id": 101,
    "name": "Rahul",
    "department": "IT",
    "salary": 40000
}

Employee Details:
ID: 101
Name: Rahul
Department: IT
Salary: 40000

Explanation

  • The employee array stores the original information.
  • json_encode() converts the array into a JSON string.
  • JSON_PRETTY_PRINT formats the JSON output.
  • json_decode() converts the JSON string back into an associative array.
  • The employee details are displayed using their array keys.

Concepts Covered

  • JSON encoding and decoding
  • json_encode()
  • json_decode()
  • Associative arrays
  • Practical employee data management

Key Takeaways

  • JSON stands for JavaScript Object Notation.
  • JSON is commonly used for exchanging data between applications.
  • json_encode() converts PHP values into JSON strings.
  • json_decode() converts JSON strings into PHP values.
  • By default, json_decode() returns objects for JSON objects.
  • Passing true as the second argument to json_decode() returns associative arrays.
  • JSON_PRETTY_PRINT makes JSON output easier to read.
  • JSON_UNESCAPED_UNICODE preserves readable Unicode characters.
  • json_last_error() helps identify JSON decoding errors.
  • json_last_error_msg() provides a readable error description.

Frequently Asked Questions (FAQs)

1. What is JSON in PHP?

JSON is a lightweight data format used to store and exchange information. PHP supports JSON through built-in encoding and decoding functions.

2. What is json_encode() in PHP?

json_encode() converts PHP values, such as arrays and objects, into a JSON-formatted string.

3. What is json_decode() in PHP?

json_decode() converts a valid JSON string into a PHP value, such as an object or associative array.

4. What is the difference between json_encode() and json_decode()?

json_encode() converts PHP data into JSON, whereas json_decode() converts JSON data into PHP values.

5. Why do we use true in json_decode()?

Passing true as the second argument converts JSON objects into associative PHP arrays instead of PHP objects.

6. What is JSON_PRETTY_PRINT?

JSON_PRETTY_PRINT is an encoding option that formats JSON with indentation and line breaks for better readability.

7. How can we check whether JSON data is valid in PHP?

You can decode the JSON and check json_last_error(). If it returns JSON_ERROR_NONE, no decoding error occurred.

8. What is JSON_UNESCAPED_UNICODE?

JSON_UNESCAPED_UNICODE is an option that keeps Unicode characters readable instead of converting them into escape sequences.

9. Can PHP convert a multidimensional array into JSON?

Yes. json_encode() can convert multidimensional PHP arrays into JSON arrays containing nested objects or arrays.

10. Where is JSON used in real-world PHP applications?

JSON is commonly used in REST APIs, web applications, mobile applications, AJAX requests, and communication between frontend and backend systems.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top