Thursday, October 23, 2025
HomeLanguagesPHP | JsonSerializable jsonSerialize() Function

PHP | JsonSerializable jsonSerialize() Function

The JsonSerializable::jsonSerialize() function is an inbuilt function in PHP which is used to serialize the JSON object to a value that can be serialized natively by using json_encode() function.

Syntax:

mixed JsonSerializable::jsonSerialize( void )

Parameters: This function does not accept any parameters.

Return Value: This function returns the data which is serialized by json_encode() function.

Below programs illustrate the JsonSerializable::jsonSerialize() function in PHP:

Program 1:




<?php 
class vector implements JsonSerializable { 
    public function __construct(array $arr) { 
        $this->array = $arr; 
    } 
  
    public function jsonSerialize() { 
        return $this->array; 
    } 
} 
  
// Declare an array 
$arr = [1, 2, 3, 4, 5]; 
  
echo("JSON elements:\n"); 
  
// Convert the array element into JSON
echo json_encode(new vector($arr), JSON_PRETTY_PRINT); 
  
?> 


Output:

JSON elements:
[
    1,
    2,
    3,
    4,
    5
]

Program 2:




<?php 
class vector implements JsonSerializable { 
    public function __construct(array $arr) { 
        $this->array = $arr; 
    } 
  
    public function jsonSerialize() { 
        return $this->array; 
    } 
} 
  
// Declare an array 
$arr = [
    "x" => "neveropen", 
    "y" => "for",
    "z" => "neveropen"
]; 
  
echo("Convert the array element into JSON:\n"); 
  
// Convert the array element into JSON
echo json_encode(new vector($arr), JSON_PRETTY_PRINT); 
  
?> 


Output:

Convert the array element into JSON:
{
    "x": "neveropen",
    "y": "for",
    "z": "neveropen"
}

Reference: https://www.php.net/manual/en/jsonserializable.jsonserialize.php

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS