yii2: Error return when using JSON_FORMAT with NULL value

Invoke return $this->asJson(null); in controller or $response->format = Response::FORMAT_JSON; $response->data = null;

will output nothing.

In standard json, the null value must be output a ‘null’ string. But when I set output format to json, and value is null, it output nothing. I think the right output is a ‘null’ string, hope fixed.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 17 (12 by maintainers)

Commits related to this issue

Most upvoted comments

@cebe I don’t think we should modify content directly in Controller::asJson(). The better solution is to change JsonResponseFormatter behavior like this:

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);
        } else {
            $response->content = 'null';
        }
    }

Might this not be a breaking change?

Strict correctness of the JSON encoding isn’t necessarily the requirement if Yii, according to its documentation, specifies that a PHP null means “don’t output anything”. People might be using it.

@cebe I think that use case is irrelevant here - empty string is invalid JSON. “null response” should return null encoded as JSON.

>> JSON.parse('')
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
>> JSON.parse('null')
null

https://3v4l.org/R4mRJ

Please do.

I’m ready to make PR with this change and updated tests