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

Working with JSON in PHP: A Complete Guide to Parsing and Serialization



JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in web development. PHP provides powerful built-in functions for working with JSON, allowing easy conversion between PHP structures and JSON strings. In this article, we will thoroughly examine how to perform parsing (decoding) and serialization (encoding) of JSON in PHP, as well as look at typical errors and ways to handle them.



What is JSON and why is it needed in PHP?



JSON is a text format based on JavaScript syntax. It is used to transfer structured data between a server and a client (for example, in REST APIs). In PHP, JSON is indispensable when:



  • Exchanging data with external APIs (e.g., weather services, payment systems)
  • Storing configuration files
  • Serializing data for caching
  • Working with web sockets and AJAX requests


PHP has supported working with JSON since version 5.2.0. All necessary functions are built into the core — no additional extensions are required.



Data Serialization to JSON (json_encode)



The json_encode() function converts PHP values (arrays, objects, strings, numbers) into a JSON string. Let's look at a basic example:



<?php// Associative array$user = [    'name' => 'Ivan Petrov',    'age' => 28,    'email' => 'ivan@example.com',    'is_active' => true,    'hobbies' => ['programming', 'chess', 'running']];

// Encode to JSON$jsonString = json_encode($user, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);echo $jsonString;?>


Result:



{    "name": "Ivan Petrov",    "age": 28,    "email": "ivan@example.com",    "is_active": true,    "hobbies": [        "programming",        "chess",        "running"    ]}


Important json_encode flags



  • JSON_UNESCAPED_UNICODE — preserves Cyrillic characters (without this flag, Russian characters will be escaped as \\uXXXX)
  • JSON_PRETTY_PRINT — formats output with indentation for readability
  • JSON_NUMERIC_CHECK — converts numeric strings to numbers
  • JSON_FORCE_OBJECT — forces the creation of an object, even if an empty array is passed


Parsing JSON in PHP (json_decode)



The json_decode() function performs the reverse transformation — from a JSON string to a PHP value. By default, it returns an object. To get an associative array, pass the second parameter true:



<?php$jsonString = '{"name":"Ivan Petrov","age":28,"email":"ivan@example.com","is_active":true}';

// Decode to object$userObject = json_decode($jsonString);echo $userObject->name; // Ivan Petrov

// Decode to associative array$userArray = json_decode($jsonString, true);echo $userArray['name']; // Ivan Petrov?>


Nesting depth



The third parameter of json_decode() — depth — limits the recursion depth. By default, it is 512. This protects against attacks like the "billion laughs attack":



<?php$deepJson = '{"a":{"b":{"c":{"d":"test"}}}}';$data = json_decode($deepJson, true, 3); // Error if depth is greater than 3?>


Error handling when working with JSON



When parsing invalid JSON, json_decode() returns null. To get detailed error information, use json_last_error() and json_last_error_msg():



<?php$badJson = '{"name": "Ivan", age: 28}'; // Error: key age is not in quotes

$data = json_decode($badJson, true);

if (json_last_error() !== JSON_ERROR_NONE) {

Blogs

Book Recommendations