What input will cause golang's json.Marshal to return an error?

后端 未结 4 1368
栀梦
栀梦 2020-12-09 14:29

From the docs:

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

4条回答
  •  庸人自扰
    2020-12-09 15:14

    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
    

提交回复
热议问题