Skip to content

How to return empty object in json response? #20521

@hgyncoder

Description

@hgyncoder

Problem description

In rest controller i have this method

public function actionTest() {
    return ['test' => new MyModel()];
}

This return a empty array instead object

{
    "test": []
}

expected

{
    "a": {}
}

Possible solution

Apparently the problem is in the processData($data, &$expressions, $expPrefix) of BaseJson.php

In version 2.0.13 that I used, the if ($data === []) { return new \stdClass(); } command was at the end, regardless of the type it was executed

if (is_object($data)) {
    if ($data instanceof JsExpression) {
        $token = "!{[$expPrefix=" . count($expressions) . ']}!';
        $expressions['"' . $token . '"'] = $data->expression;

        return $token;
    } elseif ($data instanceof \JsonSerializable) {
        return static::processData($data->jsonSerialize(), $expressions, $expPrefix);
    } elseif ($data instanceof Arrayable) {
        $data = $data->toArray();
    } elseif ($data instanceof \SimpleXMLElement) {
        $data = (array) $data;
    } else {
        $result = [];
        foreach ($data as $name => $value) {
            $result[$name] = $value;
        }
        $data = $result;
    }

    if ($data === []) {
        return new \stdClass();
    }
}

In the most current versions it is replaced by

} else {
    /*
    * $data type is changed to array here and its elements will be processed further
    * We must cast $data back to object later to keep intended dictionary type in JSON.
    * Revert is only done when keepObjectType flag is provided to avoid breaking BC
    */
    $revertToObject = static::$keepObjectType;

    $result = [];
    foreach ($data as $name => $value) {
        $result[$name] = $value;
    }
    $data = $result;

    // Avoid empty objects to be returned as array (would break BC without keepObjectType flag)
    if ($data === []) {
        $revertToObject = true;
    }
}

This way when $data is an Arrayable it does not check if it is empty

Additional info

Yii version: 2.0.50
PHP version: 8.2
Operating system: Windows/Debian

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions