Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_decode on a 32bit server

Tags:

json

php

32-bit

im writting a twitter mashup service. When i receive the json data, some of the twit ids are greater than 2147483647 (which is the maximum allowed integer on 32bit servers).

I came up with a solution that works, which is converting the integers to strings; that way the json_decode() function won't have any problems when trying to generate the array.

This is what i need to achieve:

Before (original JSON data)

[{"name":"john","id":5932725006},{"name":"max","id":4953467146}]

After (solution applied)

[{"name":"john","id":"5932725006"},{"name":"max","id":"4953467146"}]

I'm thinking of a preg_match implementation, but i have no idea on how to do it bullet-proof. Any help will be much appreciated.

like image 804
Andres SK Avatar asked Nov 22 '09 00:11

Andres SK


2 Answers

You can use preg_replace to capture the numbers and add the quotes, something like this:

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

Try the above example here.

like image 74
Christian C. Salvadó Avatar answered Nov 13 '22 12:11

Christian C. Salvadó


If you use PHP 5.2 those long ids will be parsed into a float, which though not ideal at least gives you another 21 bits of integer precision, which should easily be enough to store those ids. (A 64-bit server would be ideal of course.)

like image 1
bobince Avatar answered Nov 13 '22 11:11

bobince