json_encode在windows上返回整数值,在linux上返回字符串

时间:2022-09-15 11:48:54

I've this strange problem showing up lately. I'm currently developing on a Windows environment while deploying on a Linux server, I know that isn't ideal but I can't do much about it at this stage.

我最近出现了这个奇怪的问题。我目前正在Windows环境中进行开发,而在Linux服务器上进行部署,我知道这并不理想,但在这个阶段我做不了多少。

All I'm doing is getting the data from database and then returning a JSON response of the resulting array, but the result is different causing problem in my front-end app.

我正在做的就是从数据库获取数据然后返回结果数组的JSON响应,但结果不同导致我的前端应用程序出现问题。

I'm getting this on windows:

我在Windows上得到这个:

{
    "id":40,
    "name":"test"
}

and this on Linux:

这在Linux上:

{
     "id":"40",
     "name":"test"
}

I'm actually using Laravel framework and so the syntax is simply this:

我实际上使用的是Laravel框架,所以语法就是这样:

$user = User::find($id);
return Response::json($user->toArray());

Which behind the scene is doing this:

幕后背后是这样做的:

$this->data = json_encode($data);

So unluckily I don't have a hook where to set JSON_NUMERIC_CHECK option.

所以不幸的是我没有钩子在哪里设置JSON_NUMERIC_CHECK选项。

Before refactoring my code, is there a way to force JSON_NUMERIC_CHECK on all json_encode calls? I'm using the same database to fetch the data so I guess it could be a platform-related problem?

在重构我的代码之前,有没有办法在所有json_encode调用上强制JSON_NUMERIC_CHECK?我正在使用相同的数据库来获取数据,所以我猜它可能是一个与平台相关的问题?

EDIT:

Further investigations made me think that the guilty may be the database drivers. If I dump the data on windows I'm getting this:

进一步的调查使我认为有罪可能是数据库驱动程序。如果我在Windows上转储数据我得到这个:

 array
      'id' => int 40
      'name' => string 'test' (length=4)

while on Linux it's:

在Linux上它是:

array
     'id' => string '40' (length=2)
     'name' => string 'test' (length=4)

1 个解决方案

#1


6  

Laravel uses PDO and PDO uses MySQL driver. It's mysql or mysqlnd.

Laravel使用PDO和PDO使用MySQL驱动程序。这是mysql或mysqlnd。

Only mysqlnd provides correct data types. So querying integer return integer. Another drivers return all data as string. Also you can check that PDO does not use statement prepare emulation.

只有mysqlnd提供了正确的数据类型。所以查询整数返回整数。另一个驱动程序将所有数据作为字符您还可以检查PDO是否使用语句准备仿真。

#1


6  

Laravel uses PDO and PDO uses MySQL driver. It's mysql or mysqlnd.

Laravel使用PDO和PDO使用MySQL驱动程序。这是mysql或mysqlnd。

Only mysqlnd provides correct data types. So querying integer return integer. Another drivers return all data as string. Also you can check that PDO does not use statement prepare emulation.

只有mysqlnd提供了正确的数据类型。所以查询整数返回整数。另一个驱动程序将所有数据作为字符您还可以检查PDO是否使用语句准备仿真。