gremo
gremo

Reputation: 48899

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));

Upvotes: 11

Views: 3385

Answers (2)

user1883650
user1883650

Reputation: 167

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

Upvotes: 9

Jarvix
Jarvix

Reputation: 86

You could make the variables private. Then they won't show up in the JSON encoding.

If that is not an option, you could make a private array, and use the magic methods __get($key) and __set($key,$value) to set and get values in/from this array. In your case the keys would be 'empty' and 'null'. You can then still access them publicly but the JSON encoder will not find them.

class A
{
    public $yes = "...";
    private $privateVars = array();
    public function __get($key)
    {
        if (array_key_exists($key, $this->privateVars))
            return $this->privateVars[$key];
        return null;
    }
    public function __set($key, $value)
    {
        $this->privateVars[$key] = $value;
    }
}

http://www.php.net/manual/en/language.oop5.overloading.php#object.get

Upvotes: 0

Related Questions