Convert object to JSON

Published Feb 25, 2018Last updated Mar 09, 2018

Converting an array to JSON is easy. You need to follow these two simple steps:

$arrayToJson = ['name' => 'John','age' => 23];
string(24) "{"name":"John","age":23}"

But have you ever asked yourself how to convert an object into JSON?
Generally speaking, you can do that by making all the attributes public like this

class User {
  public $name;
  public $age;
$objectToJson = new User();
$objectToJson->name = 'John';
$objectToJson->age = 24;
string(24) "{"name":"John","age":24}"

When it comes to making out properties private or protected, all the data won't be available after json_encode, so we have to implement JsonSerializable.

class User implements JsonSerializable{
  private $name;
  private $age;
  public function __construct(string $name, string $age)
    $this->name = $name;
    $this->age = $age;
  public function jsonSerialize(){
    return json_encode(get_object_vars($this));
$objectToJson = new User('John', 27);
Discover and read more posts from Bart ehui
get started