K
K
Kerm2020-08-11 14:18:00
symfony
Kerm, 2020-08-11 14:18:00

JsonResponse strip array indexes from result if they start from zero?

Tell me, there is an array:

Array
(
    [List] => Array
        (
            [0] => Array
                (
                    [guid] => Пустое значение поля глобальный идентификатор региона
                )

            [1] => Array
                (
                    [guid] => Пустое значение поля глобальный идентификатор региона
                )

        )

)


In json it would be like:

{
  "List": [
    {
      "guid": "Пустое значение поля глобальный идентификатор региона"
    },
    {
      "guid": "Пустое значение поля глобальный идентификатор региона"
    }
  ]
}


And if you remove the element with index 0, then it will be like this:

"List": {
            "1": {
                "guid": "Пустое значение поля глобальный идентификатор региона"
            }
        }


How to make sure that this problem does not arise if an element with index 0 is passed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2020-08-11
@Kerm

JsonResponse has nothing to do with it. It's about json_encode. You need the JSON_FORCE_OBJECT option

use Symfony\Component\HttpFoundation\JsonResponse;

$data = [
    'List' => [
        0 => [
            'id' => 'id0',
        ],
        1 => [
            'id' => 'id1',
        ],
    ],
];
dump(
    new JsonResponse(
        json_encode($data, JsonResponse::DEFAULT_ENCODING_OPTIONS | JSON_FORCE_OBJECT),
        200,
        [],
        true
    )
);
// or
$response = new JsonResponse($data);
$response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | JSON_FORCE_OBJECT);
dump($response->getContent());

Or, if you need it regularly and in many places, you can create your own JsonResponse, which is inherited from the standard one, in which you can change the encodingOptions to the ones you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question