go type_error ai_generated true

error: json: error calling MarshalJSON for type time.Duration

ID: go/encoding-json-marshal-time-duration

Also available as: JSON · Markdown · 中文
80%Fix Rate
81%Confidence
0Evidence
2026-11-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

time.Duration does not implement json.Marshaler and is marshaled as a nanosecond integer, which may not be intended.

generic

中文

time.Duration未实现json.Marshaler,会被编组为纳秒整数,可能不符合预期。

Workarounds

  1. 90% success Create a custom type that marshals duration as string
    type Duration time.Duration
    func (d Duration) MarshalJSON() ([]byte, error) {
        return json.Marshal(time.Duration(d).String())
    }

Dead Ends

Common approaches that don't work:

  1. Using string formatting to convert duration 60% fail

    Inconsistent output; use custom type with MarshalJSON.