所以我在WAMP环境中使用php 5.2.6.
我正在尝试使用json_decode函数将json字符串转换为数组.JSON来自其他地方的REST API,因此我无法控制JSON字符串的格式.这是我正在尝试使用的json字符串之一的示例:
[{
"webinarKey":795855906,
"sessionKey":100000000041808257,
"startTime":"2011-12-16T13:56:15Z",
"endTime":"2011-12-16T14:48:37Z",
"registrantsAttended":2
}]
Run Code Online (Sandbox Code Playgroud)
我特意在这里找到sessionKey值.PHP将值视为一个浮点数,我似乎无法做任何事情来检索原始值.
我尝试过以下方法:
json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
# This produces the following error because my php version isn't up to snuff and I
# can't upgrade to the version required
# Warning: json_decode() expects at most 2 parameters, 4 given
Run Code Online (Sandbox Code Playgroud)
我也试过这个:
$json_obj = json_decode($json, true);
number_format($json_obj[0]["sessionKey"], 0, '.', '');
# This results in precision issues where the value was 100000000041808257
# but is number_formated out as 100000000041808256
Run Code Online (Sandbox Code Playgroud)
正如我所说,升级到php 5.4(支持4参数json_decode调用)不是一个选项.请帮忙!
谢谢!
要使用质量JSON规范:
// wrap numbers
$json = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $json);
// as object
$object = json_decode($json);
// as array
$array = json_decode($json, true);
Run Code Online (Sandbox Code Playgroud)
感谢@Scott Gottreu 和@pospi。
答案是在这个问题的已接受答案的最后评论中。
使用 preg_replace() 函数将所有整数值用引号引起来。
json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $jsonString), true);
Run Code Online (Sandbox Code Playgroud)
实际上,在测试上述行之后,它用浮点数作为值来搞乱 JSON,因此为了解决该问题,我使用以下命令将所有数字(整数或浮点数)括在引号中:
json_decode(preg_replace('/("\w+"):(\d+(\.\d+)?)/', '\\1:"\\2"', $jsonString), true);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4054 次 |
| 最近记录: |