Ingro
Ingro

Reputation: 2841

json_encode return integer values on windows and string on linux

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.

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.

I'm getting this on windows:

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

and this on Linux:

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

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

$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.

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?

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:

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

while on Linux it's:

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

Upvotes: 4

Views: 1463

Answers (1)

gureedo
gureedo

Reputation: 315

Laravel uses PDO and PDO uses MySQL driver. It's mysql or 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.

Upvotes: 6

Related Questions