Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MikeFromHL's avatar

Output Empty Arrays and Objects in JSON

I'm developing an API and need to be able to output empty arrays and objects in the returned JSON. However, I'm running into a problem where empty objects/dicts are returned as empty arrays.

Example Request Body:

{
    "attributes": {
        "empty_array": [],
        "empty_object": {}
    }
}

Actual Response:

{
    "attributes": {
        "empty_array": [],
        "empty_object": []
    }
}

Expected Response:

{
    "attributes": {
        "empty_array": [],
        "empty_object": {}
    }
}

In the model, I am casting the attribute to an ArrayObject:

    protected $casts = [
        'attributes' => AsArrayObject::class
    ];

And then in the controller, the model is handed off to an API resource:

    public function store(StoreCustomerRequest $request)
    {
        return new CustomerResource(Customer::create($request->validated()));
    }

The API resource:

    public function toArray($request)
    {
        return [
            'attributes' => $this->attributes
        ];
    }

I'm not sure what I'm missing or doing wrong to be able to have all instances of arrays and objects/dicts (no matter the nesting level) represented in the returned JSON.

0 likes
10 replies
Sinnbeck's avatar

To return an empty array as {} you can cast it

'foo' => (object) [], 
MikeFromHL's avatar

@Sinnbeck True, but how about deeply nested arrays/objects? Are you saying I'd need to traverse the request and check for empty objects to cast in that way? If so, how can I check for empty objects in the request? It seems to be converted to an array in the request with no way to differentiate between an object and array.

Sinnbeck's avatar

But php has no way of knowing an empty array should be an object unless you tell it to

MikeFromHL's avatar

@Sinnbeck The problem I have is that the structure of the JSON payload for the attributes is arbitrary, so I won't know what should be an array and what should be an object. I am trying to think of a way to parse the JSON before it is decoded and cast instances of {} in the way you described (object) []. Does that sound like the right approach?

MikeFromHL's avatar

@arturminelli I was incorrectly casting the attribute. I changed it to this to get it working:

use App\Casts\Json;

protected $casts = [
    'attributes' => Json::class
];
2 likes

Please or to participate in this conversation.