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

时间:2015-05-07 18:19:33

标签: php json numbers

我想预先解析一个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 修复了第二个浮点值。它有两点。

6 个答案:

答案 0 :(得分:3)

使用json_decode($jsonString, false, 512, JSON_BIGINT_AS_STRING)选项:

<?php require 'PHPMailer/PHPMailerAutoload.php'; function Selectdata($table,$condition) { global $conn,$result,$selectarray,$rowcount; $sql="SELECT * from ".$table." ".$condition." "; $result=$conn->query($sql); $rowcount=$result->num_rows; $selectarray = array(); while($row=$result->fetch_assoc()) { $selectarray[]=$row; } return $result; } // function for join function outerjoin($query) { global $conn,$result,$selectoutter,$rowcount; $sql="".$query.""; $result=$conn->query($sql); $rowcount=$result->num_rows; $selectoutter = array(); while($row=$result->fetch_assoc()) { $selectoutter[]=$row; } } $mail = new PHPMailer; $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'kumaresh.arun93@gmail.com'; $mail->Password = 'xxxxxxxxxxxxx'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; $mail->SMTPDebug = 1; $mail->setFrom('kumaresh.arun93@gmail.com', 'Arun'); $mail->addAddress('kumaresh.boss@gmail.com', 'kumaresh'); $mail->IsHTML (true); $mail->Subject = 'Messages From Forum'; $table="mdl_course"; $condition=""; $selectcourse=Selectdata($condition,$table); foreach ($selectarray as $cid) { $query="SELECT a.name as forumname,b.name as discussion,c.message,c.userid,d.firstname,d.email,d.phone1 from mdl_forum as a inner join mdl_forum_discussions b on a.id=b.forum inner join mdl_forum_posts c on b.id=c.discussion inner join mdl_user d on c.userid=d.id where a.course=".$cid['id']." and a.category=1 and from_unixtime(c.modified,'%Y-%m-%d')=CURDATE()"; $selectmsg=outerjoin($query); foreach ($selectoutter as $fmsg) { $mail->Body = '<p><b>Forum Name:</b>&nbsp;&nbsp;&nbsp;'.$fmsg['forumname'].'</p>'; $mail->Body.= '<p><b>Discussion Name:</b>&nbsp;&nbsp;&nbsp;'.$fmsg['discussion'].'</p>'; $mail->Body.= '<p><b>Message:</b>&nbsp;&nbsp;&nbsp;'.$fmsg['message'].'</p>'; } } $send = $mail->Send(); if (!$send) { echo 'Message could not be sent.'; // echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; } ?>

答案 1 :(得分:2)

使用它:它应该工作

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

答案 2 :(得分:1)

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

$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));

这是代码只替换float到string,你应该在调用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',
          ),
      ),
    )

答案 3 :(得分:1)

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

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

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

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

灵感来自这个答案,我已经调整了正则表达式以使其能够使用替换,并将其扩展为使用数组和否定https://stackoverflow.com/a/35008486

用字符串测试 {"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"}

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

答案 4 :(得分:0)

如果有人在寻找正则表达式也要匹配负数,则为:

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

答案 5 :(得分:0)

这是将此类数字括在引号中并使之成为字符串的最正确方法。这不会扭曲json字符串的原始外观,并考虑了科学格式。 Githubcomposer

Int