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:
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 writing a book on bootstrapping startups called MAKE, which you can pre-order now. And I'm now on Instagram and Twitter too if you'd like to follow more of my adventures. I don't use email so tweet me your questions.
Fixing “Inf and NaN cannot be JSON encoded” in PHP the easy way