php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #73223 json_encode() returns false when depth is 1 and a complex object is provided
Submitted: 2016-10-02 05:06 UTC Modified: 2016-10-02 05:52 UTC
From: jimmymasaru at gmail dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 5.6.26 OS: macOS
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: jimmymasaru at gmail dot com
New email:
PHP Version: OS:

 

 [2016-10-02 05:06 UTC] jimmymasaru at gmail dot com
Description:
------------
I use json_encode() with a depth (usually 1) to trim complex objects in some test cases in order to do comparisons.
But it returns false now if the object being encoded contains a member which is an object.
I have to set the depth to 2 but it means it doesn't trim like what I did before.

But I'm not sure if this bug is related to PHP 5.6.26. It might have been introduced in earlier versions.

Test script:
---------------
class Person
{
    public $name;
    public $age;
    public $role;
}

class Role
{
    public $name;
}

$person = new Person();
$person->name = 'Name';
$person->age = 20;
$person->role = new Role();
$jsonObj = json_encode($person, 0, 1);
// $jsonObj === false

Expected result:
----------------
{"name":"Name","age":20,"role":null}

Actual result:
--------------
false

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-10-02 05:52 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2016-10-02 05:52 UTC] requinix@php.net
It has always returned false. https://3v4l.org/AHvH6
As the error indicates, the problem is the depth limit: encoding reaches that limit and fails. The behavior you're seeing now is correct - it shouldn't serialize data if it cannot completely serialize the data.
If you want a method to "trim complex objects" then I would suggest get_object_vars() + filtering to remove/substitute object values + json_encode() on the resulting array.

You're getting false now and were not before? Then that means something changed besides the version of PHP. What is it? Are you using the bundled JSON implementation or one provided externally (eg, jsonc)?
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Tue Oct 06 02:00:01 2026 UTC