JSON Marshal Rejects NaN And Inf
json.Marshal fails with an unsupported value error for NaN and Inf floats, so sensor-style readings must be filtered or sanitized before encoding.
Code
package main
import (
"encoding/json"
"fmt"
"math"
)
type Reading struct {
Sensor string `json:"sensor"`
Value float64 `json:"value"`
}
func main() {
readings := []Reading{
{Sensor: "temp", Value: 21.5},
{Sensor: "probe", Value: math.NaN()},
{Sensor: "gain", Value: math.Inf(1)},
}
for _, r := range readings {
data, err := json.Marshal(r)
if err != nil {
// json.Marshal rejects NaN and Inf as unsupported values
fmt.Printf("%s: marshal error: %v\n", r.Sensor, err)
continue
}
fmt.Printf("%s: %s\n", r.Sensor, data)
}
}What the demo proves
Three readings are marshalled in a loop: a plain float, a NaN probe and a +Inf gain. The plain sensor encodes normally, while the other two fail: json.Marshal returns an UnsupportedValueError instead of emitting NaN or Infinity into the JSON output.
Because the error arrives per value, the loop keeps going: each failing reading prints its marshal error and the next sensor still encodes. That is the sanitization checkpoint — readings must be filtered, clamped, or string-encoded before they reach this call.
Points worth noting
- The error names the offending value, so the log points at the exact sensor.
- Struct tags drive the field names; the failure is about the value, not the schema.
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- Why does json.Marshal reject NaN and Inf?
- JSON has no representation for either value, so encoding/json returns an UnsupportedValueError instead of writing invalid JSON; the demo prints that error per failing reading.
Report a problem with this exampleOpens a pre-filled issue on GitHub.