I got this pesky problem this week where PHP doesn’t like to json_encode erroneous infinite (Inf) and not available (NaN) values. These might result due to math formulas in your code applied to bad (or missing) data. This is incredibly stupid because with PHP’s serialize() function NaN and Inf encode fine.
echo json_encode($array);
“”
echo json_last_error_msg();
Inf and NaN cannot be JSON encoded
PHP’s json_encode() function actually returns blank if it gets an error. You’ll need to use json_last_error_msg() to find out what’s happening. I gave up fixing the source of the data problem as it took too much time with 100,000 values. So I came up with this smart but dirty trick:
json_encode(unserialize(str_replace(array(‘NAN;’,’INF;’),’0;’,serialize($reply))));
We literally just str_replace NAN and INF with 0 and the data encodes to JSON successfully. This works because serialize doesn’t care about NaN or Inf while json_encode does.
Good luck, have fun! And don’t let PHP’s arbitrary rules win!
P.S. I'm on Twitter too if you'd like to follow more of my stories. And I wrote a book called MAKE about building startups without funding. See a list of my stories or contact me. To get an alert when I write a new blog post, you can subscribe below: