11

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

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

With this solution, "empty" and "null" will not be encoded when their values are not empty arrays or nulls. I believe this is not what the asker wanted.
0

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

2 Comments

Yes, i know that but thanks for the answer. The problem is when B extends A, B can't modify $privateVars and make it private.
Would making it protected work? Why would B make $privateVars private, it already is private.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.