Laravel 5 控制器将 JSON 整数作为字符串发送 [英] Laravel 5 controller sending JSON integer as string

查看:44
本文介绍了Laravel 5 控制器将 JSON 整数作为字符串发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的开发服务器上,来自 Laravel 5 控制器的 JSON 响应以正确的类型显示数据.

On my development server the JSON response from the Laravel 5 controller shows the data in the correct types.

例如

imdb_rating: 7.6
imdb_votes: 6271

但在生产服务器上,JSON 响应以字符串形式发回.

But on the production server, the JSON response is sent back as strings.

imdb_rating: "7.60"
imdb_votes: "6271"

开发和生产都安装了相同版本的 PHP (5.6.11-1).

Both development and production have the same version of PHP installed (5.6.11-1).

对可能导致这种行为的原因有什么想法吗?

Any ideas on what may be causing this behaviour?

推荐答案

确保使用 MySQL Native驱动程序,它将支持本机数据类型.

Make sure to use MySQL Native Driver which will support native data types.

如果使用 mysqlnd 库,可以通过设置 MYSQLI_OPT_INT_AND_FLOAT_NATIVE 连接选项将整数和浮点列转换回 PHP 数字.如果设置,mysqlnd 库将检查结果集元数据列类型并将数字 SQL 列转换为 PHP 数字,如果 PHP 数据类型值范围允许的话.这样,例如,SQL INT 列作为整数返回.

It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option, if using the mysqlnd library. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

MySQL 客户端库将所有字段作为字符串返回.

MySQL Client Library will return all fields as strings.

另一种解决方案是将 json_encode 选项与 JSON_NUMERIC_CHECK 一起使用.

Another solution would be to use json_encode options with JSON_NUMERIC_CHECK.

例如:

return response()->json(["foo" => "bar"], 200, [], JSON_NUMERIC_CHECK);

这篇关于Laravel 5 控制器将 JSON 整数作为字符串发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆