Skip to main content

PHP json_encode return empty array [] instead of empty object {}

Problem:

Get below array for example. 

$status = array("message"=>"error","club_id"=>$_club_id,"status"=>"1","membership_info"=>array(),);

This array will be encoded in json format

echo json_encode($status);

This function return json:

{"message":"error","club_id":275,"status":"1","membership_info":[]}

Notice the empty array [], it is not consistent, it should be an empty object {}

{"message":"error","club_id":275,"status":"1","membership_info":{}}

The cause:

This problem is caused by the called function array(), which yields an empty array []

Solution:

There are 2 solutions for this issue:

Solution 1:Call new stdClass instead of array(), stdClass generates an empty object {}

Solution 2:The above solution is complex in case there are plenty of arrays to work with. If so, follow this simple solution: Developer just uses normal array() function and then use flag JSON_FORCE_OBJECT when encode the array:

json_encode($status, JSON_FORCE_OBJECT);

JSON_FORCE_OBJECT (integer)
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.


Comments

  1. Casino Slot Machines - JammyRocket | JCM Hub
    Casino Slot 부산광역 출장샵 Machines 통영 출장마사지 - JCM Hub offers the 속초 출장샵 latest in video slot machines, 오산 출장샵 classic slots and some new games to entertain guests. The Casino Slot 삼척 출장안마 Machine

    ReplyDelete

Post a Comment