How to deal with the error Inf and NaN cannot be JSON encoded in php

In PHP, if you try to convert special values ​​such as Inf (positive infinity) and NaN (not a number) directly into JSON format using json_encode, the error "Inf and NaN cannot be JSON encoded" will appear. To deal with this problem, you can do one of the following:

1. Convert to valid JSON value: Replace Inf and NaN with valid values ​​supported by JSON

For example, replace Inf with a large number (such as 999999999) and replace NaN with null or the string "NaN".
Sample code:

$value = INF; // Inf or NaN value
// Convert Inf and NaN to valid JSON values
if (is_infinite($value)) {
    $value = 99999999; // Replace Inf with a large number
} elseif (is_nan($value)) {
    $value = 'NaN'; // Replace NaN with string "NaN"
}
$jsonData = json_encode($value);
echo $jsonData;


2. Use the JSON_PARTIAL_OUTPUT_ON_ERROR option in the json_encode function

In PHP 7.1 and higher, you can avoid errors by setting the JSON_PARTIAL_OUTPUT_ON_ERROR option and encoding Inf and NaN as null.
Sample code:

$value = INF; // Inf or NaN value
$jsonData = json_encode($value, JSON_PARTIAL_OUTPUT_ON_ERROR);
echo $jsonData;

Guess you like

Origin blog.csdn.net/jkzyx123/article/details/132340162