How to get around or make PHP json_decode not alter my very large integer values?

北战南征 提交于 2019-11-26 17:19:50

问题


So I'm using php 5.2.6 in a WAMP environment.

I'm trying to use the json_decode function to make a json string into an array. The JSON is coming from a REST API elsewhere so I have no control over formatting of the JSON string. Here is an example of one of the json strings I'm trying to use:

[{
    "webinarKey":795855906,
    "sessionKey":100000000041808257,
    "startTime":"2011-12-16T13:56:15Z",
    "endTime":"2011-12-16T14:48:37Z",
    "registrantsAttended":2
}]

I'm specifically after the sessionKey value here. PHP is treating the value as a float and I can't seem to do anything to retrieve the original value.

I've tried the following:

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

I've also tried this:

$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

As I said, upgrading to php 5.4 (where the 4 parameter json_decode call is supported) isn't an option. Please help!

Thanks!


回答1:


To quality JSON spec use:

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



回答2:


Thanks @Scott Gottreu and @pospi.

The answer was in the last comment for the accepted answer on this question.

Use the preg_replace() function to surround all integer values with quotes.

json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $jsonString), true);

Actually after testing the above line it screws up JSON with floating point numbers in as values so to fix that issue I used the following to just enclose all numbers (integer or floating point numbers) in quotes:

json_decode(preg_replace('/("\w+"):(\d+(\.\d+)?)/', '\\1:"\\2"', $jsonString), true);



回答3:


Meanwhile, PHP has fixed this problem ... well, somehow. Starting sometime around PHP 5.4 they added an option which does the just what the Regex solutions posted above do:

json_decode($json, false, 512, JSON_BIGINT_AS_STRING);

The 512 refers to the default maximum nesting depth.



来源:https://stackoverflow.com/questions/8759314/how-to-get-around-or-make-php-json-decode-not-alter-my-very-large-integer-values

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