PHP json_decode integers and floats to string

泪湿孤枕 提交于 2019-12-18 08:19:08

问题


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"
}

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


回答1:


Use this: It should work

echo preg_replace('/\: *([0-9]+\.?[0-9e+\-]*)/', ':"\\1"', $jsonString);



回答2:


Use JSON_BIGINT_AS_STRING option:

json_decode($jsonString, false, 512, JSON_BIGINT_AS_STRING)




回答3:


I like this is solution for big float:

$json = '{"data":[[0.00004639,683724.2687321],[0.00004658,190091.61007863]]}';

$json = preg_replace('/([0-9]+)\.([0-9]+)/', '"$1.$2"', $json);

print_r(json_decode($json, true));

This is code replace only float to string and you should use it before call json_decode()

JSON:

{"data":[[0.00004639,683724.2687321],[0.00004658,190091.61007863]]}

After decode:

 array (
      'data' => array (
          0 => array (
            0 => '0.00004639',
            1 => '683724.2687321',
          ),
          1 => array (
            0 => '0.00004658',
            1 => '190091.61007863',
          ),
      ),
    )



回答4:


If anyone was looking for regex to match also negative numbers, here it is:

echo preg_replace('/\: *([0-9]+\.?[0-9e+\-]*|-[0-9]+\.?[0-9e+\-]*)/', ':"\\1"', $jsonString);


来源:https://stackoverflow.com/questions/30108803/php-json-decode-integers-and-floats-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!