josecelano josecelano -5 years ago 424
JSON Question

PHP json_decode integers and floats to string

I want to pre-parse a json an convert all numbers in the json (integers or float) to strings.

For example:

"integer": 10000,
"big_integer": 100000999499498485845848584584584,
"float1" : 1.121212,
"float2" : 8.226347662837406e+09

to this:

"integer": "10000",
"big_integer": "100000999499498485845848584584584",
"float1" : "1.121212",
"float2" : "8226347662.837406"

I have found the following but it does not work for floats:

$jsonString = '[{"name":"john","id":5932725006},{"name":"max","id":4953467146}]';

echo preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $jsonString);
//prints [{"name":"john","id":"5932725006"},{"name":"max","id":"4953467146"}]

Update 2 Fixed second float value. It had two points.

Answer Source

Use this: It should work

echo preg_replace('/\: *([0-9]+\.?[0-9e+\-]*)/', ':"\\1"', $jsonString);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download