Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control json_encode behavior?

Is there any way to control json_encode behavior on objects? Like excluding empty arrays, null fields and so on?

I mean something like when using serialize(), where you can implement magic __sleep() method and specify what properties should be serialized:

class MyClass
{
   public $yes   = "I should be encoded/serialized!";
   public $empty = array(); // // Do not encode me!
   public $null  = null; // Do not encode me!

   public function __sleep() { return array('yes'); }
}

$obj = new MyClass();
var_dump(json_encode($obj));
like image 728
gremo Avatar asked Jan 08 '12 13:01

gremo


1 Answers

The most correct solution is extending the interface JsonSerializable;

by using this interface you just need to return with the function jsonSerialize() what you want json_encode to encode instead of your class.

Using your example:

class MyClass implements JsonSerializable{

   public $yes   = "I should be encoded/serialized!";
   public $empty = array(); // // Do not encode me!
   public $null  = null; // Do not encode me!

   function jsonSerialize() {
           return Array('yes'=>$this->yes);// Encode this array instead of the current element
   }
   public function __sleep() { return array('yes'); }//this works with serialize()
}

$obj = new MyClass();
echo json_encode($obj); //This should return {yes:"I should be encoded/serialized!"}

Note: this works in php >= 5.4 http://php.net/manual/en/class.jsonserializable.php

like image 162
user1883650 Avatar answered Oct 19 '22 06:10

user1883650