Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With json_encode, is there a way to force certain values not to be converted into numeric?

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.

like image 534
Firemyst Avatar asked Dec 07 '25 06:12

Firemyst


1 Answers

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.

like image 109
Ulrich Eckhardt Avatar answered Dec 09 '25 18:12

Ulrich Eckhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!