PHP json_decode 整数和浮点数到字符串

PHP json_decode integers and floats to string

我想预解析 json 并将 json 中的所有数字(整数或浮点数)转换为字符串。

例如:

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

对此:

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

更新 我找到了 following 但它不适用于花车:

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

更新 2 固定第二个浮点值。它有两点。

使用这个:它应该可以工作

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

使用 JSON_BIGINT_AS_STRING 选项:

json_decode($jsonString, false, 512, JSON_BIGINT_AS_STRING)

我喜欢这是大浮动的解决方案:

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

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

print_r(json_decode($json, true));

这是仅将浮点数替换为字符串的代码,您应该在调用前使用它 json_decode()

JSON:

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

解码后:

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

如果有人正在寻找正则表达式来匹配负数,这里是:

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

这是将此类数字用引号括起来,使它们成为字符串的最正确方法。这不会扭曲 json 字符串的原始外观并考虑到科学格式。 Github (composer)

$regexp = '/"(\s*)\:(\s*)(\-?\d+([eE][\+|\-]?\d+|\.\d+)+)(\s*[,(\s*)|\}])/';
$json_string = preg_replace($regexp, ":\"\"", $json);

这是一个适用于浮点数的正则表达式,它适用于 属性 ,但也适用于 数组 。它也适用于 negative 浮点数。

preg_replace('/((?<=":)|(?<=\[)|(?<=,))(?<!")(-?\d+\.\d+)(?!")/', '""', $json)

如果您还想覆盖科学记数法,这会起作用,但这也会将整数转换为字符串

preg_replace('/((?<=":)|(?<=\[)|(?<=,))(?<!")(-?[\d\.]+((e|E)(\+|-)\d+)?)(?!")/', '""', $json)

灵感来自这个答案,我调整了正则表达式甚至可以使用替换,并将其扩展为使用数组和负数

用字符串测试 {"array":[[0.00004639,683724.2687321],[0.00004658,190091.61007863,190091.61007863]],"and_finally":{"negative_float":-1.123,"negative_int":-1,"first_name":"sa123mp5e-19le","last_name":"la5.1e+5stn543.123,ame","integer":"100","another_float":"1555.20","int":100,"float":1555.20,"floatAsString":"1555.20","date":"2015-01-01 15:23:51","somefloat":[14,23],"somefloat2":[5e-7,23.33],"scientific_negative_float":5.2e-7,"scientific_positive_float":5E+19}}

问题

如果 json 中有空格,这将失败(在生产环境中永远不会出现这种情况)。如果你有空格,那么你可以用这个删除所有空格(但是如果你在 json 中的任何地方都有句子,这会将它合并成一个长单词)

preg_replace('/\s/', '', $json)

此方法的另一个问题是,如果在字符串中找到数组匹配项,则它们是不安全的。这些将是罕见的,但它们仍然可能发生。

这会失败{"last_name":"lastn,543.123ame"}

这也会失败 {"last_name":"lastn[543.123ame"}

不幸的是,没有直接的方法可以仅使用一次正则表达式来绕过这些限制。但是,如果您的回复中只包含数字,那么这很有用!