TheStoryCoder
TheStoryCoder

Reputation: 3640

Yii2 - how to force response JSON formatter to use objects instead of arrays?

I know I can set Yii::$app->response->format = \yii\web\Response::FORMAT_JSON but how I can make it set the JSON encoding flag JSON_FORCE_OBJECT so that all arrays will be encoded as objects instead?

Upvotes: 4

Views: 706

Answers (1)

TheStoryCoder
TheStoryCoder

Reputation: 3640

Alright, it wasn't so hard:

Yii::$app->response->formatters[\yii\web\Response::FORMAT_JSON] = [
    'class' => 'yii\web\JsonResponseFormatter',
    'encodeOptions' => JSON_FORCE_OBJECT,
];

Or even as a one-liner:

Yii::$app->response->formatters[\yii\web\Response::FORMAT_JSON]['encodeOptions'] = JSON_FORCE_OBJECT;

Upvotes: 5

Related Questions