26

I'm trying to convert and array of response into JSON format. I have tried all the answers that were posted on SO and other websites like web1,web2 adding header('Content-Type: application/json') and then echo json_encode($data,JSON_PRETTY_PRINT); But I'm always getting the output in text format. Can some one help me in solving this.

Helpers Class:

public static function renderJSON($data) {
    header('Content-Type: application/json');
    echo json_encode($data,JSON_PRETTY_PRINT);
}

My Controller:

if ($model->login()) {
    $user =  User::findByUsernameOrEmail($request->post('username'));
    $userArray = ArrayHelper::toArray($user);
    Helpers::renderJSON($userArray);

I tried to printing the userArray and it looks like this:

Array
(
    [name] => abc
    [lastname] => xyz
    [username] => test_test
)

Json output: (html/text)

{
    "name": "abc",
    "lastname": "xyz",
    "username": "test_test"
}
rob006
  • 21,383
  • 5
  • 53
  • 74
ASN
  • 1,655
  • 4
  • 24
  • 52

5 Answers5

55

Set

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

in the controller's action somewhere before return.

Bizley
  • 17,392
  • 5
  • 49
  • 59
  • Thanks Bizley. It's working. Can I add it in the `helper class` before the `echo` statement instead, as I will be calling that function at different places. – ASN Jan 16 '17 at 11:16
  • First of all you should `return` data and not `echo` it. It can be anywhere as long as it affects current response. – Bizley Jan 16 '17 at 11:18
  • ok Bizley. I will change it to return instead of echo (but changing it to return is giving me empty result. I'm checking the code on postman and there is nothing in the output). And I added the statement in `behaviors()` method in controller – ASN Jan 16 '17 at 11:22
  • By adding `\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;` you don't need to use any Helper classes, not even `$userArray = ArrayHelper::toArray($user);`, just try to return `$user` – marche Jan 16 '17 at 16:26
  • @ASN see my answer below – Yasar Arafath Aug 08 '17 at 11:14
54

Since Yii 2.0.11 there is a dedicated asJson() method to return a response in JSON format. Run:

return $this->asJson($array);

in your controller action.

rob006
  • 21,383
  • 5
  • 53
  • 74
Andreas Hinderberger
  • 1,505
  • 23
  • 41
  • If returning a big chunk of HTML it works really slow, can't get why – Oleg Mar 04 '22 at 10:16
  • 1
    Try to disable debugging completely and see whether that improves the loading time. I have several Yii2 projects that had loading time issues and by step by step disabling modules/components I found that it was the Yii2-debug component which slowed the whole application server side down. – Andreas Hinderberger Mar 04 '22 at 14:50
7

Simply Add this in controller

public function beforeAction($action)
{

    \Yii::$app->response->format = Response::FORMAT_JSON;
    return parent::beforeAction($action);
}
Yasar Arafath
  • 605
  • 1
  • 9
  • 30
1
use yii\helpers\Json;
use yii\web\Response;

Firstly include the 2 lines above at the top of your controller, then in any of your Controller actions, just before the return statements, include the below

Yii::$app->response->format = Response::FORMAT_JSON;
return Json::encode([
            'message' => 'success'
]);

You can build the return array as you deem fit.

manglide
  • 85
  • 1
  • 10
1
use JsonException;
use yii\web\NotFoundHttpException;
use yii\base\InvalidConfigException;
use yii\web\Response;
use yii\web\JsonResponseFormatter;


/**
 * @param int $id
 * @return string[]
 * @throws InvalidConfigException
 * @throws JsonException
 * @throws NotFoundHttpException
 */
public function actionViewJson(): array
{
    Yii::$app->response->format = Response::FORMAT_JSON;
    Yii::$app->response->formatters = [
        Response::FORMAT_JSON => [
            'class' => JsonResponseFormatter::class,
            'prettyPrint' => true
        ]
    ];
    
    return ['key' => 'val'];
}       
Ivošš
  • 1,106
  • 12
  • 18