3

When using PHP (5.4/5.5) and json_encode(), I'm having some issues when using the JSON_NUMERIC_CHECK option. This is on a system in production, so I can't simply remove the option, as this would change the entire response and break client parsing.

Sample code:

$var = array("id" => 1195756, "hash" => "7e12");
echo json_encode($var) . "\n";
echo json_encode($var, JSON_NUMERIC_CHECK) . "\n";

Output:

{"id":1195756,"hash":"7e12"}
{"id":1195756,"hash":7000000000000}

The later is not what I want. "7e12" is a valid hash for our system. I realize it's also loose scientific notation, but how can I force the value to stay as a string?

Note: Using strval() had no effect.

Community
  • 1
  • 1
Firemyst
  • 73
  • 5
  • JSON_BIGINT_AS_STRING is it useful ? – Onur Feb 23 '16 at 20:07
  • 3
    `JSON_NUMERIC_CHECK` is telling it to encode numeric strings as numbers and you are passing a numeric string. The only option is to not use `JSON_NUMERIC_CHECK` or don't pass a numeric string. – AbraCadaver Feb 23 '16 at 20:08
  • *"I got this working snippet and this not working snippet, how can I get the latter to work. "* - Well, use the first one. – GolezTrol Feb 23 '16 at 20:31
  • @Onur: no, it made no difference. – Firemyst Feb 23 '16 at 20:35
  • Onur. That might work for this particular value, although I don't know if this value is considered 'big' enough. But integers with scientific notation (or strings appearing to be integers with scientific notation) can also evaluate to small integer values, for instance `"7e2"` in which case it certainly won't work. – GolezTrol Feb 23 '16 at 20:37
  • JSON_BIGINT_AS_STRING won't trigger with scientific notation. If the number is actually identified as such, it's formatted with proper notation (ie. 7.0e+14), but is not a string. – Firemyst Feb 23 '16 at 20:40

1 Answers1

3

Instead of using strval() on the fields that should stay strings, use intval() or floatval() on fields that should be numeric. In other words, give the JSON encoder the correct types. Then, you don't need JSON_NUMERIC_CHECK to fix up things that should have been numbers to start with.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
  • 1
    This is the direction I ended up taking, using `(int)` to force numeric data where I wanted it. PDO/mysql returns all strings, so had to do something. – Firemyst Feb 25 '16 at 22:49