Laravel 5.6如何在json响应中保留float和int值?

时间:2018-11-13 09:08:51

标签: php json laravel

搜索大约20分钟,仍然找不到可靠的答案,如何简单地将json respone配置为float类型。

$array = DB::select('SELECT name, balance FROM ... blah blah blah'); // balance is float

return response()->json([
   'data' => $array
]);

它返回:

{"data":[
   {"name":"bob","balance":"889.37700000000018"},
   {"name":"john","balance":"705.77400000000011"}
]}

因此,您可能会想,我想在此json数据中使用浮点类型来获取余额值:

{"data":[
   {"name":"bob","balance":889.37700000000018},
   {"name":"john","balance":705.77400000000011}
]}

我可以使用带有json_encode()标志的标准JSON_PRESERVE_ZERO_FRACTION函数来解决此问题。

但是如何使用response()->json()做同样的事情?

我尝试过此示例,但失败了,并且发生了错误:

return response()->json([
      'data' => $array
   ],
   Response::HTTP_OK,
   [],
   JSON_PRESERVE_ZERO_FRACTION
);

2 个答案:

答案 0 :(得分:2)

您可以通过提供映射为

来投射模型属性
class UserModel {

    // mention mapping to primitive data-types as [int, float, boolean, decimal, real, array, object]
    protected $casts = array(
        "is_admin" => "boolean",
        "age" => "integer",
        "salary" => "float",
        "certificates" => "array"
    );
}

生成的序列化模型JSON将根据您的映射进行转换。

[
    {
        "is_admin": true,
        "age": 30,
        "salary":  100.12,
        "cetificates": []
    }
]

答案 1 :(得分:0)

我通过对查询结果进行排序并将余额值转换为浮动在foreach循环中来解决了该问题。

$array= [];

foreach($result as $row) {
   array_push($array, [
      'name' => $row->name,
      'balance' => (float) $row->balance
   ]);
}

return response()->json([
   'data' => $array
]);