go type_error ai_generated true

错误:json:调用time.Duration类型的MarshalJSON时出错

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
81%置信度
0证据数
2026-11-15首次发现

版本兼容性

版本状态引入弃用备注
1.20 active
1.21 active

根因分析

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

English

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

generic

解决方案

  1. 90% 成功率 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())
    }

无效尝试

常见但无效的做法:

  1. Using string formatting to convert duration 60% 失败

    Inconsistent output; use custom type with MarshalJSON.