Lets convert JSON_decode float values to strings

I was working on my Custom Facebook Feed plugin and recently ran into an issue. When using PHP’s json_decode function to parse the JSON data returned from Facebook it would convert certain ID values to floats instead of giving them to me as strings or just plain old integers. These IDs weren’t too much longer than the other IDs which were being processed as strings, but those couple of extra numbers meant that the function returned them as floats instead.

For example; an ID might be formatted like this in the JSON:

"eid": 123456789012345,

In it’s infinite wisdom, json_decode decided to return this large value as a float like so:

1.234567890123+03

This wasn’t very useful to me as I needed the exact ID, number for number. After a lot of research and trial and error I found a solution which did the trick.

 

The solution

Use a preg_replace to wrap the number in quotes in the JSON string and then the decode function will return it as a string! Genius, right? So before you pass the JSON string to the json_decode function you run a preg_replace on it to wrap the IDs in question in quotes. The function then interprets them as strings and not integers.

Here’s how to do it:

$json_string = preg_replace('/"eid":(\d+)/', '"eid":"$1"', $json_string);
$parsed_json_data = json_decode($json_string );

This finds all instances of “eid”: in the JSON string, and wraps the proceeding integer in quotes. This then returns the ID value as “123456789012345”. As it’s unlikely that you’re also trying to parse ‘eid’ values then just replace ‘eid’ with the item you’re trying to parse.

Boom. Problem solved.

One much appreciated response...

  1. Alex says:

    Many thanks John, I got into the same issue with facebook batch requests, and your workaround solved it! thanks

    I use it like this for multiple replacements:

    $json_keys = array(‘/”object_id”:(\d+)/’, ‘/”fromid”:(\d+)/’);
    $json_keys_replaces = array(‘”object_id”:”$1″‘, ‘”fromid”:”$1″‘);
    $faceCommentRequestString = preg_replace($json_keys, $json_keys_replaces, $faceCommentRequest[‘body’]);

Feel free to add your comment..

Your email address will not be published.