What input will cause golang's json.Marshal to

2019-02-11 19:03发布

From the docs:

JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an infinite recursion.

I've experienced this situation, which results in a runtime panic.

What I'm wondering is if anyone can provide a working program that demonstrates a non-panic situation where json.Marshal returns a non-nil error. The best answers would clearly include the inputs used.

2条回答
家丑人穷心不美
2楼-- · 2019-02-11 19:30

Update: now using a channel instead of a map[int]int to elicit the error


Go-specific structures,e.g. func or chan refuse to serialize:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    value := make(chan int)
    _, err := json.Marshal(value)
    fmt.Println(err)
}
查看更多
小情绪 Triste *
3楼-- · 2019-02-11 19:41

Just to complement Jonathan's answer, the json.Marshal function can return two types of errors: UnsupportedTypeError or UnsupportedValueError

The first one can be caused, as Jonathan said by trying to Marshal an invalid type:

_, err := json.Marshal(make(chan int))
_, ok := err.(*json.UnsupportedTypeError) // ok == true

On the other hand you can also have the Marshal function return an error by passing an invalid value:

_, err := json.Marshal(math.Inf(1))
_, ok := err.(*json.UnsupportedValueError) // ok == true
查看更多
登录 后发表回答