16

I am using PHP's PDO to query a MySQL database. It returns numbers and integers as strings, and is messing with my JSON.

Is there a better way of fixing it other than type casting the values row by row?

array(2) { 
  ["name"]=> string(11) "Preliminary" 
  ["sell_price"]=> string(6) "864.00"
} 
Florent
  • 12,310
  • 10
  • 49
  • 58
user1032531
  • 24,767
  • 68
  • 217
  • 387

2 Answers2

11

If you are using php 5.3.3 or higher you can use JSON_NUMERIC_CHECK as the second argument to json_encode to do this.

See: http://us3.php.net/manual/en/function.json-encode.php

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 3
    Good answer. Thanks. Note this warning however which describes how a phone number like '+33123456789' will be converted to an integer. http://us3.php.net/manual/en/function.json-encode.php#106641 – user1032531 Aug 22 '12 at 16:57
  • 5
    All the answers here are ugly hacks. For the correct solution, see [this answer](http://stackoverflow.com/a/20123337/229792). – jameshfisher Apr 03 '14 at 14:42
  • `JSON_NUMERIC_CHECK` is not suitable in some cases. Like one given [here](http://php.net/manual/en/function.json-encode.php#106641). But what is the reason mysql driver returns integer as string? Isn't there any better way!! – Salman Sep 19 '14 at 07:13
3

Although @Explosion Pills works in this case for @user1032531's needs, it's not addressing the 1st source of the problem.

As you can see in the original question, on the PHP side the value from sell_price is already a string, although, as the user said, in the database it's stored as a "number" (we don't know if it's a DECIMAL or a FLOAT).

Well, when using PDO with MySQL a proper config may be required in order to get "numbers" as "numbers", as user @jameshfisher pointed out in his comment. You can follow his link in order to get almost everything you need to get it working.

Appart from that, the accepted answer is working because without the use of the JSON_NUMERIC_CHECK json_encode will send everything as text no matter the type of the variable, and when using it it will convert the value to a type based on guesses rather than the type of the original var.

Community
  • 1
  • 1
Pere
  • 1,068
  • 12
  • 20