63

I have this code

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

echo json_encode($status);

This function return json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}

But I need json like this:

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

5
  • 2
    that is how json represents an array. [] stands for an array in Json Commented Jan 28, 2015 at 10:07
  • 1
    What is the problem with the current format? Commented Jan 28, 2015 at 10:08
  • This is the correct json format. Arrays are enclosed in Braces - "[ ]". Commented Jan 28, 2015 at 10:30
  • 7
    @jogesh_pi The issue is that it generates inconsistent json (array when empty and object when not). Other parsers have issues with this: stackoverflow.com/questions/26725138/… Commented Oct 18, 2017 at 13:11
  • 2
    The first three comments here are not correct. Commented Feb 27, 2019 at 19:57

5 Answers 5

114

use the JSON_FORCE_OBJECT option of json_encode:

json_encode($status, JSON_FORCE_OBJECT);

Documentation

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.

Or, if you want to preserve your "other" arrays inside your object, don't use the previous answer, just use this:

$status = array(
                "message"=>"error",
                "club_id"=>$_club_id,
                "status"=>"1",
                "membership_info"=> new stdClass()
                );
Sign up to request clarification or add additional context in comments.

3 Comments

yeah the problem is that arrays like ["one"] are then transformed into an object two, which is wrong.
The answer here answers the OP's question. You need to look at other answers to partially preserve arrays inside objects.
Bottom line: DO NOT use JSON_FORCE_OBJECT (unless you want your normal arrays mangled/curly-bracified). And in your JSON tree you must validate each object node for being empty and manually cast it to object or replace with new StdClass() ...
42
$status = array(
                "message"=>"error",
                "club_id"=>$_club_id,
                "status"=>"1",
                "membership_info"=>(object) array(),
                );

By casting the array into an object, json_encode will always use braces instead of brackets for the value (even when empty).

This is useful when can't use JSON_FORCE_OBJECT and when you can't (or don't want) to use an actual object for the value.

Comments

8

There's no difference in PHP between an array and an "object" (in the JSON sense of the word). If you want to force all arrays to be encoded as JSON objects, set the JSON_FORCE_OBJECT flag, available since PHP 5.3. See http://php.net/json_encode. Note that this will apply to all arrays.

Alternatively you could actually use objects in your PHP code instead of arrays:

$data = new stdClass;
$data->foo = 'bar';
...

Maybe it's simpler to handle the edge case of empty arrays client-side.

Comments

1

While this may not be considered elegant, a simple string replace can effectively address this.

str_replace("[]", "{}", json_encode($data));

This mitigates the issue of JSON_FORCE_OBJECT converting a normal array into an object.

1 Comment

This won't work if there's [] inside a string: str_replace('[]', '{}', json_encode(['key' => '[]'])) --> {"key":"{}"}
1

I know this is an old question, but it's among the first hits on Google, so I thought I should share an alternative solution.

Rather than using standard PHP arrays, in PHP 7+ you can instead use Map() as part of the Data Structure extension. Documentation.

A Map object has practically identical performance as arrays and also implements ArrayAccess so it can be accessed as a regular array. Contrary to a standard array, however, it will always be associative and works as expected with json_encode. It also has some other minor benefits like object keys and better memory handling.

Some example usage:

use Ds\Map;

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

$map = new Map(); 
print json_encode($map); // {}

$map = new Map();
$map["foo"] = "bar";
print json_encode($map); // {"foo":"bar"}
print $map["foo"]; // bar

$map = new Map();
$map[1] = "foo";
$map[2] = "bar";
$map[3] = "baz"; 
print json_encode($map); // {"1":"foo","2":"bar","3":"baz"}

1 Comment

it's a good solution but worth noticing that Data Structures is not a built-in PHP extension. It needs to be installed before use. The installation instructions are available on php.net.

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.