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


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:

$query = new Query;
$query->select('id, number, name')
		      ->where(['active' => 1])
			  	['like', 'name', $q],
			  	['like', 'number', $q]
	$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, can be closed, sorry.

1 Like


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.