Working with JSON in PHP: Parsing and Data Serialization

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: why does PHP need JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the de facto standard for web APIs, configuration files, and storing structured information. Despite its origins in JavaScript, JSON is perfectly supported in all modern programming languages, including PHP.

In PHP, working with JSON is implemented natively through two key functions: json_encode() (serialization — converting PHP data into a JSON string) and json_decode() (deserialization — parsing a JSON string back into PHP structures). In this article, we will thoroughly examine how to effectively use these tools, handle errors, and apply JSON in real projects.



1. Data serialization: the json_encode() function

The json_encode() function converts a PHP value (array, object, string, number) into a JSON format string. This is necessary when you want to send data to a client (for example, via AJAX) or save it to a file.



Basic syntax and examples

<?php// Simple array$colors = ["red", "green", "blue"];echo json_encode($colors);// Output: ["red","green","blue"]

// Associative array$user = [ "name" => "Ivan", "age" => 30, "is_admin" => false];echo json_encode($user);// Output: {"name":"Ivan","age":30,"is_admin":false}?>


Useful json_encode() flags

The function supports a second parameter — a bitmask of flags. Let's look at the most useful ones:

  • JSON_PRETTY_PRINT — formats the output with indentation for readability.
  • JSON_UNESCAPED_UNICODE — does not escape Cyrillic and other Unicode characters (otherwise Russian letters will turn into \\uXXXX).
  • JSON_NUMERIC_CHECK — converts strings containing numbers into a numeric type.
  • JSON_FORCE_OBJECT — forcibly turns an array into an object even for indexed arrays.


<?php$data = ["name" => "Anna", "age" => "25"];

// Without flagsecho json_encode($data);// {"name":"\\u0410\\u043d\\u043d\\u0430","age":"25"}

// With flagsecho json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);/*{ "name": "Anna", "age": "25"}*/?>


2. Parsing JSON: the json_decode() function

The json_decode() function performs the reverse operation — it turns a JSON string back into a PHP variable. By default, it returns an object of the stdClass class, but you can request an associative array.



Parsing into an object and into an array

<?php$jsonString = '{"name":"Peter","age":28,"skills":["PHP","MySQL"]}';

// Default — object$obj = json_decode($jsonString);echo $obj->name; // Peterecho $obj->skills[0]; // PHP

// With the true flag — associative array$arr = json_decode($jsonString, true);echo $arr["name"]; // Peterecho $arr["skills"][1]; // MySQL?>


Recursion depth

The third parameter depth limits the nesting depth. The default is 512 levels. This is protection against "billion laughs attack" type attacks:

<?php$malicious = '{"a":{"b":{"c":"d"}}}';$result = json_decode($malicious, false, 2); // Maximum 2 levels// Will return null because depth is exceeded?>


3. Error handling when working with JSON

One of the most common problems is an invalid JSON string. PHP does not throw an exception on a parsing error, but returns null. To understand what went wrong, use the json_last_error() and json_last_error_msg() functions.



Error checking

<?php$badJson = '{"name": "Error, missing quote}';$data = json_decode($badJson);

if (json_last_error() !== JSON_ERROR_NONE) { echo "JSON error: " . json_last_error_msg();?>

Blogs

Book Recommendations