jsonutil

package module
v0.0.0-...-135cbae Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 14 Imported by: 15 modules, 7 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Reference Code Coverage License

Code Coverage

jsonutil is a Go package that provides custom JSON v2 marshaling and unmarshaling functions for specific data types.

This package is particularly useful when you need to handle JSON encoding and decoding for types like time.Duration and url.URL in a customized manner.

Features

  • Custom marshaler and unmarshaler for url.URL:
    • URLMarshal marshals url.URL as a string.
    • URLUnmarshal unmarshals url.URL from a string.
  • Custom marshalers and unmarshalers for time.Duration:
    • DurationMarshalIntSeconds marshals time.Duration as an integer representing seconds.
    • DurationUnmarshalIntSeconds unmarshals time.Duration from an integer assuming it represents seconds.
    • DurationMarshalString marshals time.Duration as a string in its canonical units, such as "1h30m" or "500ms".
    • DurationUnmarshalString unmarshals time.Duration from such a string, parsed with time.ParseDuration.
  • Custom marshalers and unmarshalers for time.Time:
    • TimeMarshalIntUnix marshals time.Time as an integer representing unix time.
    • TimeUnmarshalIntUnix unmarshals time.Time from an integer assuming it represents unix time.
    • TimeUnmarshalStringOrIntUnix unmarshals time.Time from an RFC 3339 string, or a string such as "Mon Jan 2 2006 15:04:05 MST-0700", or an integer representing unix time. Null and the empty string are the zero time.
    • TimeMarshalIntUnixFor(names...) and TimeUnmarshalIntUnixFor(names...) return a marshaler and an unmarshaler that do as TimeMarshalIntUnix and TimeUnmarshalIntUnix do, but only for the times held by an object member of one of the names given, or by an array such a member holds. Any other time is left to the next (un)marshaler, or to the default string: for an API that writes some times as unix time and others as strings.
    • TimeUnmarshalEmptyAsZero unmarshals time.Time from an empty string as the zero time, and from anything else as time.Time itself does.
  • Custom marshalers and unmarshalers for civil.Date:
    • DateMarshalIntUnix marshals civil.Date as an integer representing the unix time of its midnight UTC.
    • DateUnmarshalIntUnix unmarshals civil.Date from such an integer, reading the day in UTC.
    • DateMarshalIntUnixFor(names...) and DateUnmarshalIntUnixFor(names...) do as the two above, but only for the dates held by an object member of one of the names given, as TimeMarshalIntUnixFor does for times.
    • DateMarshalBasic marshals civil.Date as a string in ISO 8601's basic form, without separators, such as "20260320".
    • DateUnmarshalBasic unmarshals civil.Date from such a string, or from null as the zero date, which DateMarshalBasic writes as null.
    • DateMarshalBasicFor(names...) and DateUnmarshalBasicFor(names...) do as the two above, but only for the dates held by an object member of one of the names given.
    • DateUnmarshalEmptyAsZero unmarshals civil.Date from an empty string as the zero date, and from anything else as civil.Date itself does.
  • Custom unmarshaler for float64:
    • Float64UnmarshalStringOrNumber unmarshals float64 from a number or from a string holding one, such as "9.5": for an API that sends numbers as strings, but for the odd number. Null leaves the value as it is. With a field's string option, the value is marshaled as a string too.
  • Custom marshaler for maps with ordered keys:
    • OrderedMapMarshal[M ~map[K]V, K cmp.Ordered, V any] marshals M so that the keys are sorted.
  • Custom marshaler for http.Header:
    • HTTPHeaderMarshal marshals the values of http.Header as single strings.
    • HTTPHeaderUnmarshal unmarshals the values of http.Header from single strings.
  • Reading and writing files:
    • ReadFile[T any](name, opts...) reads the JSON file name and unmarshals it into a T.
    • WriteFile[T any](name, data, opts...) marshals data and writes it to the JSON file name.

Usage

To install the library, use the following command:

go get github.com/MarkRosemaker/jsonutil

Custom Marshaling and Unmarshaling for url.URL

To use the custom marshaler and unmarshaler for url.URL, you can import the package and use the provided functions:

package main

import (
	"encoding/json/v2"
	"fmt"
	"net/url"

	"github.com/MarkRosemaker/jsonutil"
)

var jsonOpts = json.JoinOptions(
	json.WithMarshalers(json.MarshalToFunc(jsonutil.URLMarshal)),
	json.WithUnmarshalers(json.UnmarshalFromFunc(jsonutil.URLUnmarshal)),
)

type MyStruct struct {
	Foo  string  `json:"foo"`
	Link url.URL `json:"link"`
}

func main() {
	out := &MyStruct{}
	if err := json.Unmarshal([]byte(`{"foo":"bar","link":"https://example.com/"}`), out, jsonOpts); err != nil {
		panic(err)
	}

	if out.Link.String() != "https://example.com/" {
		panic("something went wrong")
	}

	res, err := json.Marshal(MyStruct{
		Foo:  "baz",
		Link: url.URL{Scheme: "http", Host: "example.com", Path: "/some-path"},
	}, jsonOpts)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(res))
	// Output: {"foo":"baz","link":"http://example.com/some-path"}
}

Custom Marshaling and Unmarshaling for time.Duration

To use the custom marshaler and unmarshaler for time.Duration, you can import the package and use the provided functions:

package main

import (
	"encoding/json/v2"
	"fmt"
	"time"

	"github.com/MarkRosemaker/jsonutil"
)

var jsonOpts = json.JoinOptions(
	json.WithMarshalers(json.MarshalToFunc(jsonutil.DurationMarshalIntSeconds)),
	json.WithUnmarshalers(json.UnmarshalFromFunc(jsonutil.DurationUnmarshalIntSeconds)),
)

type MyStruct struct {
	Foo      string        `json:"foo"`
	Duration time.Duration `json:"duration"`
}

func main() {
	out := &MyStruct{}
	if err := json.Unmarshal([]byte(`{"foo":"bar","duration":3}`), out, jsonOpts); err != nil {
		panic(err)
	}

	if out.Duration != 3*time.Second {
		panic("something went wrong")
	}

	res, err := json.Marshal(MyStruct{
		Foo:      "baz",
		Duration: time.Minute,
	}, jsonOpts)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(res))
	// Output: {"foo":"baz","duration":60}
}

Custom Marshaling for Maps with Ordered Keys

To use the custom marshaler for M where [M ~map[K]V, K cmp.Ordered, V any], you can import the package and use the provided functions:

package main

import (
	"encoding/json/v2"
	"fmt"

	"github.com/MarkRosemaker/jsonutil"
)

type myMap map[string]int

var jsonOpts = json.JoinOptions(
	json.WithMarshalers(json.MarshalToFunc(jsonutil.OrderedMapMarshal[myMap])),
)

func main() {
	res, err := json.Marshal(myMap{
		"foo": 1,
		"bar": 2,
	}, jsonOpts)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(res))
	// Output: {"bar":2,"bar":1}
}

Custom Marshaling and Unmarshaling for http.Header

To use the custom marshaler and unmarshaler for http.Header, you can import the package and use the provided functions:

package main

import (
	"encoding/json/v2"
	"fmt"
	"net/http"

	"github.com/MarkRosemaker/jsonutil"
)

var jsonOpts = json.JoinOptions(
	json.WithMarshalers(json.MarshalToFunc(jsonutil.HTTPHeaderMarshal)),
	json.WithUnmarshalers(json.UnmarshalFromFunc(jsonutil.HTTPHeaderUnmarshal)),
)

func main() {
	out := &http.Header{}
	if err := json.Unmarshal([]byte(`{"foo":"bar","baz":"quux"}`), out, jsonOpts); err != nil {
		panic(err)
	}

	res, err := json.Marshal(http.Header{
		"foo": []string{"bar"},
		"baz": []string{"quux"},
	}, jsonOpts)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(res))
	// Output: {"Foo":"bar","Baz":"quux"}
}

Numbers Sent as Strings

For an API that sends a number as a string, such as "9.5", but now and then as a number, unmarshal with Float64UnmarshalStringOrNumber and give the field the string option, so that it is marshaled as the string again:

package main

import (
	"encoding/json/v2"
	"fmt"

	"github.com/MarkRosemaker/jsonutil"
)

var jsonOpts = json.WithUnmarshalers(json.UnmarshalFromFunc(jsonutil.Float64UnmarshalStringOrNumber))

type Option struct {
	Strike float64 `json:"strike,string"`
}

func main() {
	for _, in := range []string{`{"strike":"9.5"}`, `{"strike":0.0}`} {
		out := &Option{}
		if err := json.Unmarshal([]byte(in), out, jsonOpts); err != nil {
			panic(err)
		}

		fmt.Println(out.Strike)
	}

	res, err := json.Marshal(Option{Strike: 52})
	if err != nil {
		panic(err)
	}

	fmt.Println(string(res))
	// Output:
	// 9.5
	// 0
	// {"strike":"52"}
}

Unix Time for Some Members Only

Where an API writes some dates or times as unix time and others as strings, name the members holding the former:

package main

import (
	"encoding/json/v2"
	"fmt"
	"time"

	"github.com/MarkRosemaker/jsonutil"
)

var jsonOpts = json.JoinOptions(
	json.WithMarshalers(json.MarshalToFunc(jsonutil.TimeMarshalIntUnixFor("at"))),
	json.WithUnmarshalers(json.UnmarshalFromFunc(jsonutil.TimeUnmarshalIntUnixFor("at"))),
)

type Event struct {
	At      time.Time `json:"at"`
	Created time.Time `json:"created"`
}

func main() {
	t := time.Unix(1759190400, 0).UTC()

	res, err := json.Marshal(Event{At: t, Created: t}, jsonOpts)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(res))
	// Output: {"at":1759190400,"created":"2025-09-30T00:00:00Z"}
}

Additional Information

Contributing

Contributions are welcome — please open an issue or a pull request on GitHub.

License

This project is licensed under the Apache 2.0 License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DateMarshalBasic

func DateMarshalBasic(enc *jsontext.Encoder, d civil.Date) error

DateMarshalBasic is a custom marshaler for civil.Date, marshaling them as strings in ISO 8601's basic form, without separators, such as "20260320". The zero date marshals as null.

func DateMarshalBasicFor

func DateMarshalBasicFor(names ...string) func(*jsontext.Encoder, civil.Date) error

DateMarshalBasicFor returns a marshaler for civil.Date that writes, as DateMarshalBasic does, the dates held by an object member of one of the names given, or by an array such a member holds; see DateMarshalIntUnixFor.

func DateMarshalIntUnix

func DateMarshalIntUnix(enc *jsontext.Encoder, d civil.Date) error

DateMarshalIntUnix is a custom marshaler for civil.Date, marshaling them as integers representing unix time.

func DateMarshalIntUnixFor

func DateMarshalIntUnixFor(names ...string) func(*jsontext.Encoder, civil.Date) error

DateMarshalIntUnixFor returns a marshaler for civil.Date that writes, as DateMarshalIntUnix does, the dates held by an object member of one of the names given, or by an array such a member holds. It leaves any other date to the marshaler after it, or to the default, which writes a string: for an API that writes some dates as unix time and others as strings.

func DateMarshalZeroAsNull

func DateMarshalZeroAsNull(enc *jsontext.Encoder, d civil.Date) error

DateMarshalZeroAsNull is a custom marshaler for civil.Date that writes the zero date as null, where civil.Date itself would write "0000-00-00", a date that does not exist and that no decoder reads back; null reads back as the zero date. It leaves every other date to civil.Date itself, or to a marshaler joined after it.

func DateUnmarshalBasic

func DateUnmarshalBasic(dec *jsontext.Decoder, d *civil.Date) error

DateUnmarshalBasic is a custom unmarshaler for civil.Date, unmarshaling them from strings in ISO 8601's basic form, such as "20260320". Null unmarshals as the zero date.

func DateUnmarshalBasicFor

func DateUnmarshalBasicFor(names ...string) func(*jsontext.Decoder, *civil.Date) error

DateUnmarshalBasicFor returns an unmarshaler for civil.Date that reads, as DateUnmarshalBasic does, the dates held by an object member of one of the names given, or by an array such a member holds; see DateMarshalIntUnixFor.

func DateUnmarshalEmptyAsZero

func DateUnmarshalEmptyAsZero(dec *jsontext.Decoder, d *civil.Date) error

DateUnmarshalEmptyAsZero is a custom unmarshaler for civil.Date that reads an empty string as the zero date, as an API that leaves a date out may send, and anything else as civil.Date itself does.

func DateUnmarshalIntUnix

func DateUnmarshalIntUnix(dec *jsontext.Decoder, d *civil.Date) error

DateUnmarshalIntUnix is a custom unmarshaler for civil.Date, unmarshaling them from integers and assuming they represent unix time.

func DateUnmarshalIntUnixFor

func DateUnmarshalIntUnixFor(names ...string) func(*jsontext.Decoder, *civil.Date) error

DateUnmarshalIntUnixFor returns an unmarshaler for civil.Date that reads, as DateUnmarshalIntUnix does, the dates held by an object member of one of the names given, or by an array such a member holds; see DateMarshalIntUnixFor.

func DurationMarshalIntSeconds

func DurationMarshalIntSeconds(enc *jsontext.Encoder, d time.Duration) error

DurationMarshalIntSeconds is a custom marshaler for time.Duration, marshaling them as integers representing seconds.

func DurationMarshalString

func DurationMarshalString(enc *jsontext.Encoder, d time.Duration) error

DurationMarshalString encodes a time.Duration as a JSON string using the canonical units format (e.g. "1h30m", "500ms").

func DurationUnmarshalIntSeconds

func DurationUnmarshalIntSeconds(dec *jsontext.Decoder, d *time.Duration) error

DurationUnmarshalIntSeconds is a custom unmarshaler for time.Duration, unmarshaling them from integers and assuming they represent seconds.

func DurationUnmarshalString

func DurationUnmarshalString(dec *jsontext.Decoder, d *time.Duration) error

DurationUnmarshalString decodes a JSON string into a time.Duration by parsing it with time.ParseDuration.

func Float64UnmarshalStringOrNumber

func Float64UnmarshalStringOrNumber(dec *jsontext.Decoder, f *float64) error

Float64UnmarshalStringOrNumber is a custom unmarshaler for float64, unmarshaling them from a JSON number or from a string holding one, such as "9.5", as an API that sends numbers as strings does, but for the odd number. Null leaves f as it is.

func HTTPHeaderMarshal

func HTTPHeaderMarshal(enc *jsontext.Encoder, m http.Header) error

HTTPHeaderMarshal is a custom marshaler for http.Header, marshaling values as a single strings. It also marshals the keys in their canonical form. Note that we omit keys that don't have a value.

func HTTPHeaderUnmarshal

func HTTPHeaderUnmarshal(dec *jsontext.Decoder, h *http.Header) error

HTTPHeaderUnmarshal is a custom unmarshaler for http.Header, unmarshaling values as single strings or, as other tools record them, lists of strings.

func OrderedMapMarshal

func OrderedMapMarshal[M ~map[K]V, K cmp.Ordered, V any](enc *jsontext.Encoder, m M) error

OrderedMapMarshal is a custom marshaler for maps with ordered keys, marshaling them in an ordered fashion.

func ReadFile

func ReadFile[T any](name string, opts ...json.Options) (T, error)

ReadFile reads a json file and unmarshals it.

func TimeMarshalIntUnix

func TimeMarshalIntUnix(enc *jsontext.Encoder, t time.Time) error

TimeMarshalIntUnix is a custom marshaler for time.Time, marshaling them as integers representing unix time.

func TimeMarshalIntUnixFor

func TimeMarshalIntUnixFor(names ...string) func(*jsontext.Encoder, time.Time) error

TimeMarshalIntUnixFor returns a marshaler for time.Time that writes, as TimeMarshalIntUnix does, the times held by an object member of one of the names given, or by an array such a member holds; see DateMarshalIntUnixFor.

func TimeMarshalIntUnixMilli

func TimeMarshalIntUnixMilli(enc *jsontext.Encoder, t time.Time) error

TimeMarshalIntUnixMilli is a custom marshaler for time.Time, marshaling them as integers representing unix time in milliseconds.

func TimeMarshalIntUnixMilliFor

func TimeMarshalIntUnixMilliFor(names ...string) func(*jsontext.Encoder, time.Time) error

TimeMarshalIntUnixMilliFor returns a marshaler for time.Time that writes, as TimeMarshalIntUnixMilli does, the times held by an object member of one of the names given, or by an array such a member holds; see DateMarshalIntUnixFor.

func TimeUnmarshalEmptyAsZero

func TimeUnmarshalEmptyAsZero(dec *jsontext.Decoder, t *time.Time) error

TimeUnmarshalEmptyAsZero is a custom unmarshaler for time.Time that reads an empty string as the zero time, as an API that leaves a time out may send, and anything else as time.Time itself does.

func TimeUnmarshalIntUnix

func TimeUnmarshalIntUnix(dec *jsontext.Decoder, d *time.Time) error

TimeUnmarshalIntUnix is a custom unmarshaler for time.Time, unmarshaling them from integers and assuming they represent unix time.

func TimeUnmarshalIntUnixFor

func TimeUnmarshalIntUnixFor(names ...string) func(*jsontext.Decoder, *time.Time) error

TimeUnmarshalIntUnixFor returns an unmarshaler for time.Time that reads, as TimeUnmarshalIntUnix does, the times held by an object member of one of the names given, or by an array such a member holds; see DateMarshalIntUnixFor.

func TimeUnmarshalIntUnixMilli

func TimeUnmarshalIntUnixMilli(dec *jsontext.Decoder, d *time.Time) error

TimeUnmarshalIntUnixMilli is a custom unmarshaler for time.Time, unmarshaling them from integers representing unix time in milliseconds.

func TimeUnmarshalIntUnixMilliFor

func TimeUnmarshalIntUnixMilliFor(names ...string) func(*jsontext.Decoder, *time.Time) error

TimeUnmarshalIntUnixMilliFor returns an unmarshaler for time.Time that reads, as TimeUnmarshalIntUnixMilli does, the times held by an object member of one of the names given, or by an array such a member holds; see DateMarshalIntUnixFor.

func TimeUnmarshalStringOrIntUnix

func TimeUnmarshalStringOrIntUnix(dec *jsontext.Decoder, d *time.Time) error

TimeUnmarshalStringOrIntUnix unmarshals a time.Time from either an RFC3339 or timeAltLayout string, or an integer representing unix seconds or, from 10^11 on, unix milliseconds (see [unixSecondsOrMilli]). Null and the empty string decode as the zero time.

func URLMarshal

func URLMarshal(enc *jsontext.Encoder, u url.URL) error

URLMarshal is a custom marshaler for URL values, marshaling them as strings.

func URLUnmarshal

func URLUnmarshal(dec *jsontext.Decoder, u *url.URL) error

URLUnmarshal is a custom unmarshaler for URL values, unmarshaling them from strings.

func WriteFile

func WriteFile[T any](name string, data T, opts ...json.Options) error

WriteFile writes a json file by marshalling it.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址