PHP: Wie kann man Unendlich- oder NaN-Zahlen in JSON kodieren?

Offensichtlich sind Unendlich und NaN kein Teil der JSON-Spezifikation, daher dieser PHP-Code:

$numbers = array();
$numbers ['positive_infinity'] = +INF;
$numbers ['negative_infinity'] = -INF;
$numbers ['not_a_number'] = NAN;
$array_print = print_r ($numbers, true);
$array_json = json_encode ($numbers);
echo "\nprint_r(): $array_print";
echo "\njson_encode(): $array_json";

Erzeugt dies:

PHP Warning:  json_encode(): double INF does not conform to the JSON spec, encoded as 0 in /home/septi/test.php on line 8
PHP Warning:  json_encode(): double -INF does not conform to the JSON spec, encoded as 0 in /home/septi/test.php on line 8
PHP Warning:  json_encode(): double NAN does not conform to the JSON spec, encoded as 0 in /home/septi/test.php on line 8

print_r(): Array
(
    [positive_infinity] => INF
    [negative_infinity] => -INF
    [not_a_number] => NAN
)

json_encode(): {"positive_infinity":0,"negative_infinity":0,"not_a_number":0}

Gibt es eine Möglichkeit, diese Zahlen korrekt zu kodieren, ohne meine eigenen zu schreiben?json_encode() Funktion? Vielleicht ein Workaround?

Antworten auf die Frage(5)

Ihre Antwort auf die Frage