Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...