After upgrade to 2.0.16: JSON.parse: unexpected non-whitespace character after JSON data

Hello,

after upgrading to 2.0.16 I have some problem with JSON.With 2.0.15 everything worked and I didn’t change anything there:

Code
$query = new Query;
$query->select('id, number, name')
		      ->from('checklisten')
		      ->where(['active' => 1])
		      ->andWhere(['or',
			  	['like', 'name', $q],
			  	['like', 'number', $q]
			  ])
		      ->orderBy('name');
	$command = $query->createCommand();
	$data = $command->queryAll();
	$out = [];
	foreach ($data as $d) {
	     $out[] = ['value' => $d['id'], 'name' => $d['name'], 'number' => $d['number']];
	}
	echo \yii\helpers\Json::encode($out);

which comes to an error

I know the “null” is wrong here, but where does it come from? In Changelog I read there was a change in JSON, might this be the source of the problem?

Thanks, Beate

Update: After changing yii\web\JsonResponseFormatter.php (the elseif part)
protected function formatJson($response)
{
if ($response->data !== null) {
$options = $this->encodeOptions;
if ($this->prettyPrint) {
$options |= JSON_PRETTY_PRINT;
}
$response->content = Json::encode($response->data, $options);
} /* elseif ($response->content === null) {
$response->content = ‘null’;
} */
}
it now works again.

Fixed with this bug https://github.com/yiisoft/yii2/issues/17111, can be closed, sorry.

1 Like

Hey,

If you’re in a controller action, you should return Json::encode instead of echoing it.

You could also use Yii::$app->response->format = Response::FORMAT_JSON; return $out;

And let yii encode that Json for you.