Laravel 5.6 how to preserve float and int values in json response?

我怕爱的太早我们不能终老 提交于 2021-01-27 19:09:22

问题


Searching about 20 minutes and still can't find reliable answer how to simply configure json respone for float type.

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

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

It returns:

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

So, as you might guess I want to have float type in this json data for balance values:

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

I can use standard json_encode() function with JSON_PRESERVE_ZERO_FRACTION flag to solve this issue.

But how to do the same thing with response()->json() ?

I've tried this sample but it fails and error occurs:

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

回答1:


You can casts your model attributes by providing a mapping as

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"
    );
}

Resulted serialized model JSON will be casted as per your mappings.

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



回答2:


I solved it by sorting query result and casting balance value to float in foreach loop.

$array= [];

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

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


来源:https://stackoverflow.com/questions/53277393/laravel-5-6-how-to-preserve-float-and-int-values-in-json-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!