Chris
Chris

Reputation: 7184

How can I make Symfony serialize empty associative arrays as empty JSON objects?

I need to serialize a set of PHP associative arrays to JSON using Symfony. Some of these arrays happen to be empty.

This means that all arrays containing data will be serialized to JSON objects whereas all empty arrays will be serialized to JSON empty arrays. Since I would like to avoid having to check whether something is an object or an array, I would prefer if all my arrays (empty or not) would be serialized to JSON objects, not arrays.

How can I achieve this with Symfony 2?

Upvotes: 2

Views: 4786

Answers (2)

AngryUbuntuNerd
AngryUbuntuNerd

Reputation: 820

Since Symfony 4.4 there is a new option preserve_empty_objects that helps you - if you can convert the empty array into an empty object first:

$array = ['foo' => new stdClass()];
$serializer->serialize($array, "json", ["preserve_empty_objects" => true]);
// {'foo': {}}

Upvotes: -1

Chris
Chris

Reputation: 7184

Symfony 2 allows you to pass a context to the serializer in which you can set serialization options. I could not find this in the official documentation but saw it while looking through the source code.

In order to serialize empty PHP arrays to empty JSON objects you need to pass a flag to json_encode (which is what the Symfony JSON encoder uses). You can pass arbitrary flags, basically all the options that json_encode accepts.

It works like this:

$serializer->serialize($myObject, "json", ["json_encode_options" => JSON_FORCE_OBJECT])

Upvotes: 4

Related Questions