简体   繁体   English

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

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

Searching about 20 minutes and still can't find reliable answer how to simply configure json respone for float type.搜索了大约 20 分钟,仍然找不到可靠的答案如何简单地为浮动类型配置 json 响应。

$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:因此,正如您可能猜到的那样,我希望在此 json 数据中为余额值设置浮点类型:

{"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.我可以使用带有JSON_PRESERVE_ZERO_FRACTION标志的标准json_encode()函数来解决这个问题。

But how to do the same thing with response()->json() ?但是如何用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
);

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.结果序列化模型JSON将根据您的映射进行转换。

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

I solved it by sorting query result and casting balance value to float in foreach loop.我通过对查询结果进行排序并将余额值转换为在 foreach 循环中浮动来解决它。

$array= [];

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM