什么输入会导致golang的json.Marshal返回一个错误? [英] What input will cause golang's json.Marshal to return an error?

查看:1579
本文介绍了什么输入会导致golang的json.Marshal返回一个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自文档


JSON不能表示循环数据结构,而Marshal不处理它们。将循环结构传递给Marshal将导致无限递归。


我遇到过这种情况,这会导致运行时恐慌。 / p>

我想知道的是,如果任何人都可以提供一个工作程序来演示json.Marshal返回非零错误的非紧急情况。最好的答案是显然包括使用的输入。

解决方案

为了补充Jonathan的回答,json .Marshal函数可以返回两种类型的错误: UnsupportedTypeError UnsupportedValueError



第一个是可能造成的,正如Jonathan所说,试图对一个无效类型进行编组:

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

另一方面,您也可以通过传递无效值来使Marshal函数返回错误:

  _,err:= json.Marshal(math.Inf(1))
_,ok:= err。(* json.UnsupportedValueError)// ok == true


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.

解决方案

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

这篇关于什么输入会导致golang的json.Marshal返回一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆