Skip to content

encoding/json/v2: format of map values #76369

Description

@rothskeller

Go version

go version go1.25.0 darwin/amd64

Output of go env in your module/workspace:

AR='ar'
CC='clang'
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_ENABLED='1'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
CXX='clang++'
GCCGO='gccgo'
GO111MODULE=''
GOAMD64='v1'
GOARCH='amd64'
GOAUTH='netrc'
GOBIN=''
GOCACHE='/Users/stever/Library/Caches/go-build'
GOCACHEPROG=''
GODEBUG=''
GOENV='/Users/stever/Library/Application Support/go/env'
GOEXE=''
GOEXPERIMENT='jsonv2'
GOFIPS140='off'
GOFLAGS=''
GOGCCFLAGS='-fPIC -arch x86_64 -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/3y/936sl4d50dd_38rvrs041qn80000gn/T/go-build1330506723=/tmp/go-build -gno-record-gcc-switches -fno-common'
GOHOSTARCH='amd64'
GOHOSTOS='darwin'
GOINSECURE=''
GOMOD='/Users/stever/src/packet/v2/go.mod'
GOMODCACHE='/Users/stever/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='darwin'
GOPATH='/Users/stever/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/usr/local/go'
GOSUMDB='sum.golang.org'
GOTELEMETRY='on'
GOTELEMETRYDIR='/Users/stever/Library/Application Support/go/telemetry'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/local/go/pkg/tool/darwin_amd64'
GOVCS=''
GOVERSION='go1.25.0'
GOWORK=''
PKG_CONFIG='pkg-config'

What did you do?

Marshaled a structure including a map of time values with a format string.

package main

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

type S struct {
	MT map[string]time.Time `json:"mt,format:'2006-01-02'"`
}

func main() {
	var s = S{MT: map[string]time.Time{"hello": time.Now()}}
	if err := json.MarshalWrite(os.Stdout, s); err != nil {
		fmt.Println(err.Error())
	}
}

What did you see happen?

JSON v2 interpreted the format string as applying to the map, rather than to the map values, and rejected it:

json: cannot marshal from Go map[string]time.Time within "/mt": invalid format flag "2006-01-02"

What did you expect to see?

I expected it to use the format string to format the time values in the map. Attempting to interpret it as a format string for the map itself is pointless since maps don't have format strings. Or, if the 'format' specifier has to apply to the map itself, there should be some other way to specify the format string for the map values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolNeedsDecisionFeedback is required from experts, contributors, and/or the community before a change can be made.

    Type

    No type

    Projects

    Status
    Post-proposal

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions