Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode() Inf and NaN cannot be JSON encoded

Tags:

json

php

I am encoding my array into JSON and below is the case in which it gives Inf and NaN cannot be JSON encoded error

$test = ['key' => '6E01400'];
json_encode($test, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);

I understand it considers 'E' in a key as an exponent and tries to convert into a number something like 6.0 e+1400...I don't know not sure though.

Is there anyway I can avoid that conversion for special case like this one, I really need to use JSON_NUMERIC_CHECK option here, any clue guys?

like image 932
Vish021 Avatar asked Oct 27 '15 20:10

Vish021


People also ask

What does json_encode mean?

The json_encode() function is used to encode a value to JSON format.

What is json_encode and Json_decode in PHP?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.


1 Answers

There is a workaround for this in PHP 5.5.0 and above so that you can still get JSON to output, but it does rewrite your data.

The JSON_PARTIAL_OUTPUT_ON_ERROR option can be set on json_encode, if you are getting back a JSON_ERROR_INF_OR_NAN. The PHP doc says that in the case of the NAN or INF value, "0 will be encoded in the place of these special numbers."

like image 149
Sean Fahey Avatar answered Sep 30 '22 03:09

Sean Fahey