JsonResponse选项参数

时间:2018-02-08 09:26:30

标签: json laravel

在控制器中我有:

return response()->json(
    [
        'number' => (float)8
    ],
    Response::HTTP_OK,
    [],
    JSON_PRESERVE_ZERO_FRACTION
);

这是输出:

{
    "number": 8
}

是否可以获得8.0? 这个工作好:

json_encode(['number' => (float)8],JSON_PRESERVE_ZERO_FRACTION);

更新: 当我将response()->json从上方设置为$variable然后print_r($variable)时,我得到了这个:

(所以它看起来很有效,但是在浏览器中返回时我仍然得到8而不是8.0)

Illuminate\Http\JsonResponse Object
(
    [data:protected] => {"number":8.0}
    [callback:protected] => 
    [encodingOptions:protected] => 1024
    [headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
        (
            [computedCacheControl:protected] => Array
                (
                    [no-cache] => 1
                    [private] => 1
                )

            [cookies:protected] => Array
                (
                )

            [headerNames:protected] => Array
                (
                    [cache-control] => Cache-Control
                    [date] => Date
                    [content-type] => Content-Type
                )

            [headers:protected] => Array
                (
                    [cache-control] => Array
                        (
                            [0] => no-cache, private
                        )

                    [date] => Array
                        (
                            [0] => Thu, 08 Feb 2018 11:27:34 GMT
                        )

                    [content-type] => Array
                        (
                            [0] => application/json
                        )

                )

            [cacheControl:protected] => Array
                (
                )

        )

    [content:protected] => {"number":8.0}
    [version:protected] => 1.0
    [statusCode:protected] => 200
    [statusText:protected] => OK
    [charset:protected] => 
    [original] => Array
        (
            [number] => 8
        )

    [exception] => 
)

1 个答案:

答案 0 :(得分:2)

使用number_format()

json_encode(['number' => number_format(8, 1)]);

如果数字以字符串形式出现,请使用(float)$stringNumber代替$stringNumber