Duration Marshals To Integer Nanoseconds
time.Duration is an int64, so json.Marshal emits integer nanoseconds by default; a custom MarshalJSON emits the 1h30m0s string instead.
Code
package main
import (
"encoding/json"
"fmt"
"strconv"
"time"
)
// PrettyDuration 用自定义类型接管编码:底层仍是 int64,可无损互转
type PrettyDuration time.Duration
func (p PrettyDuration) MarshalJSON() ([]byte, error) {
return []byte(strconv.Quote(time.Duration(p).String())), nil
}
func main() {
duration := 90 * time.Minute
// time.Duration 底层是 int64:默认编码成纳秒整数,跨语言消费端拿到的是天数字段
nanos, _ := json.Marshal(duration)
fmt.Println("default:", string(nanos))
// MarshalJSON 输出人类可读字符串
pretty, _ := json.Marshal(PrettyDuration(duration))
fmt.Println("pretty: ", string(pretty))
// 转回 Duration 继续参与运算,零拷贝
elapsed := time.Duration(PrettyDuration(90 * time.Minute))
fmt.Println("under 2h:", elapsed < 2*time.Hour)
}From first line to last
Everything happens inside the functions MarshalJSON and main.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
Signature: func (p PrettyDuration) MarshalJSON() ([]byte, error)
The demo output is labeled (default:, pretty:, under 2h:), so the operation behind every printed line is easy to name.
Key statements
func (p PrettyDuration) MarshalJSON() ([]byte, error) {
return []byte(strconv.Quote(time.Duration(p).String())), nil
}
Interactive Tools for This Topic
Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.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.
FAQ
- What does Duration Marshals To Integer Nanoseconds print when run?
- Invoke the file as-is — the `default:`, `pretty:`, `under 2h:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.