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.

GoData Integrity

Code

gosnippet
30 lines
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

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.