json_encode($object) - ignoring null properties

3,183 views
Skip to first unread message

Ido

unread,
Apr 19, 2009, 7:10:59 AM4/19/09
to php-json
Hi all,

I'm using json_encode to encode a tree structure represented by
objects.

My object looks something like:

class TreeNode
{
public $data = array();
public $children = null;

public function addChild(TreeNode $child) {
if ($this->children == null) {
$this->children = array();
}

$this->children[] = $child;
}
}


All works well except for one thing: when no children were added to
the TreeNode, and so $children remains null - I need the json output
to NOT INCLUDE the children property.
currently what I'm seeing in my json is ..."children":null... which is
not good for me. I want no reference to the children property in the
json in this case.

Is there a way to tell json_encode to skip null properties ?
Is there a way to get more fine grained controller over the
serialization process ?

10x,
Ido

james...@firstinvestors.com

unread,
Apr 20, 2009, 9:18:10 AM4/20/09
to php-...@googlegroups.com
The short answer is "no".

What I've done in the past to solve this sort of problem is to write a special getter that returns an associative array (or object) in the format you want, then call json_encode on the return value. In your case, it might be implemented something like this:

function get_data()
{
$values = array('data' => $this->data);
if($this->children) {
$values['children'] = array();
foreach($this->children as $child)
$values['children'][] = $child->get_data();
}
}

Here I'm assuming that $children is an array of TreeNode objects (or null).

Then you would call it like this:

json_encode($node->get_data());

HTH,
-
James Jones Administrative Data Mgmt.
Webmaster 375 Raritan Center Pkwy, Suite A
Data Architect Edison, NJ 08837

Ido

unread,
Apr 20, 2009, 9:52:08 AM4/20/09
to php-json
Thanks James,
good idea !

james...@firstinvestors.com

unread,
Apr 20, 2009, 9:53:54 AM4/20/09
to php-...@googlegroups.com
And I've forgotten the "return $values" at the end of my function.... I'm always making that silly mistake!
Reply all
Reply to author
Forward
0 new messages