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.
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:
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 wrote a book on building indie startups called MAKE. And I'm on Twitter too if you'd like to follow more of my stories. I don't use email so tweet me your questions. Or you can see my list of posts. To get an alert when I write a new blog post, you can subscribe below:Follow @levelsio