reflect.SliceOf unimplemented: encoding/json (jsonv2, default in Go 1.27) panics when marshaling maps with non-string keys
Go 1.27 turns the jsonv2 experiment on by default, so the standard encoding/json package is now backed by encoding/json/v2. When it marshals a map with non-string keys and two or more entries, v2 calls reflect.SliceOf, which TinyGo stubs with panic("unimplemented: reflect.SliceOf()"). As a result, a plain json.Marshal(map[int]int{0: 1, 1: 2}) panics under TinyGo when it builds against Go 1.27.
Environment
tinygo version 0.42.0 linux/amd64 (using go version go1.27.1 and LLVM version 22.1.4)-target wasm. The failing call is in portable reflect code, so I expect other targets to be affected too, but I only tested wasm.
Reproducer
package main
import (
"encoding/json"
"fmt"
)
func main() {
b, err := json.Marshal(map[int]int{0: 1}) // one entry: fine
fmt.Println(string(b), err)
b, err = json.Marshal(map[int]int{0: 1, 1: 2}) // two entries: panics
fmt.Println(string(b), err)
}$ tinygo run -target wasm .
{"0":1} <nil>
panic: unimplemented: reflect.SliceOf()
RuntimeError: unreachable
at main.runtime._panic
at main.internal/reflectlite.SliceOf
at main.reflect.SliceOf
at main.encoding/json/v2.makeMapArshaler$2
...Results
| Go used by TinyGo | GOEXPERIMENT |
2-entry map[int]int |
|---|---|---|
| go1.25.8 | (default) | ok |
| go1.26.5 | (default) | ok |
| go1.25.8 / go1.26.5 | jsonv2 |
panic |
| go1.27.1 | (default, jsonv2 on) | panic |
| go1.27.1 | nojsonv2 |
ok |
Standard Go 1.27.1 (go run) prints {"0":1,"1":2} for the same program.
Where it comes from
src/encoding/json/v2/arshal_default.go (go1.27.1), in the map marshaler. json.Marshal requests deterministic output, so for more than one entry with a non-string key type it takes the sorting branch:
keys := reflect.MakeSlice(reflect.SliceOf(t.Key()), n, n) // line 910
vals := reflect.MakeSlice(reflect.SliceOf(t.Elem()), n, n) // line 911String-keyed maps take a different branch and are fine. json.Unmarshal into int-keyed maps (empty or not) also worked in my tests.
Workaround
Build with GOEXPERIMENT=nojsonv2. As I understand it, that experiment is meant to go away in a future Go release, so this only buys time.
Impact
We hit this in production code running on Cloudflare Workers: responses that contained a map[int][]int with more than one entry never returned. The Workers runtime reported "code had hung", not a panic, which made the cause hard to find.
Related
- #2115 (
MapOfand friends are missing, since 2022/2023) - #4804 / #4836: the
SliceOf/MapOf/... stubs were added so thatgo-json-experimentcompiles; the implementation is still missing ("Underlying implementation is still missing")
The limitation isn't new. What Go 1.27 changes is that the standard library's json.Marshal now reaches it by default, for any map keyed by an integer type.
Source: tinygo-org/tinygo