Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array to json in yii2

Tags:

rest

yii2

I am creating restful apis and I had a function to send response data in yii1 like this

public function sendResponse($data)
{
    header('Content-Type: application/json; charset=utf-8');
    echo CJSON::encode($data);
    exit;
}

CJSON is not available in Yii2 so how do i do it in Yii2

like image 386
Kuldeep Dangi Avatar asked Mar 08 '15 08:03

Kuldeep Dangi


3 Answers

You could use Json class in yii2 from

yii\helpers\Json;

It contain methods such as :

Json::encode();
Json::decode();

These methods directly converts yii2 activerecord objects into json array.

like image 85
Ninja Turtle Avatar answered Oct 18 '22 21:10

Ninja Turtle


No need to manually set header like that.

In the specific action / method you can set it like so:

use Yii;
use yii\web\Response;

...

public function actionIndex()
{
    Yii::$app->response->format = Response::FORMAT_JSON;
}

Then after that just return a simple array like that:

return ['param' => $value];

You can find this property in official docs here.

For more than one action using special ContentNegotiator filter is more flexible approach:

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => ContentNegotiator::className(),
            'only' => ['index', 'view']
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
            ],
        ],
    ];
}

There are more settings, you can check it in official docs.

As for the REST, base yii\rest\Controller already has it set for json and xml:

'contentNegotiator' => [
    'class' => ContentNegotiator::className(),
    'formats' => [
        'application/json' => Response::FORMAT_JSON,
        'application/xml' => Response::FORMAT_XML,
    ],
],
like image 24
arogachev Avatar answered Oct 18 '22 22:10

arogachev


::find()->asArray()->all(); wish help.

like image 3
William Ho Avatar answered Oct 18 '22 22:10

William Ho