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

查看:274
本文介绍了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天全站免登陆