JSON marshall nullable type value in database/sql Go

huangapple go评论83阅读模式
英文:

JSON marshall nullable type value in database/sql Go

问题

我正在尝试弄清楚如何在Go语言中将可空类型(字符串、整数、时间)正确地转换为JSON。我知道database/sql提供了sql.NullTimesql.NullInt等类型,但是当你将这些值转换为JSON时,你会得到类似这样的结果:

{"first_name": {
  "Value": "",
  "Valid": false,
}}

我真正想要的是:

{"first_name": null}

我知道你可以实现自己的MarshalJSON方法来实现这一点(我在这里写了一篇文章http://dennissuratna.com/marshalling-nullable-string-db-value-to-json-in-go/)

但是我想知道是否有其他更好的方法来做到这一点。我想知道其他人是否知道一种更简便的方法。

英文:

I am trying to figure out how one can properly marhsall nullable type (string, int, time) properly to JSON in Go. I know that database/sql provide sql.NullTime, sql.NullInt, etc but when you marshall these values, you get something like

{"first_name": {
  "Value": "",
  "Valid": false,
}}

What I really want is

{"first_name": null}

I understand that you can implement your own MarshalJSON to do this (I wrote about it here http://dennissuratna.com/marshalling-nullable-string-db-value-to-json-in-go/)

BUT I am wondering if anyone knows a better way to do this. I want to know other people know a less tedious way to do this.

答案1

得分: 2

可能有点晚了,但是当我搜索相同的问题时,谷歌将此页面排名较高,所以我的解决方案是定义一个特殊类型,例如对NullInt64进行附加费用,并导出JSON。

NullInt64的示例:

// NullInt64与sql.NullInt64相同
// 但是在导出为JSON时,它是null或导出的int64值
// 而不是包含Value和Valid属性的JSON
type NullInt64 struct {
sql.NullInt64
}

// NullInt64 MarshalJSON接口重新定义
func (r NullInt64) MarshalJSON() ([]byte, error) {
if r.Valid {
return json.Marshal(r.Int64)
} else {
return json.Marshal(nil)
}
}

然后将所有的sql.NullInt64替换为NullInt64。
你可以很容易地对sql.NullString做同样的操作。
希望能帮到你。

英文:

May be late, but when searching for the same problem google report this page at a high rank, so : my solution is to define special type that surcharge NullInt64 for exemple and has and export JSON

Example for NullInt64 :

// NullInt64 is the same as sql.NullInt64
// But when exported to JSON it is null or the int64 val that is exported
// not a JSON containing Value and Valid properties
type NullInt64 struct {
	sql.NullInt64
}

// NullInt64 MarshalJSON interface redefinition
func (r NullInt64) MarshalJSON() ([]byte, error) {
	if r.Valid {
		return json.Marshal(r.Int64)
	} else {
		return json.Marshal(nil)
	}
}

And then replace all sql.NullInt64 by NullInt64.
You can easily do the same for sql.NullString.
Hope it helps

答案2

得分: 1

创建一个类型,嵌入(例如)sql.NullInt,并实现json.Marshaler接口。

英文:

Create a type that embeds (e.g.) sql.NullInt and implements the json.Marshaler interface.

答案3

得分: 0

如果你真的想要一个空字段,你将不得不使用自定义的编组器(或者也许只是使用结构体中的*string字段,并将其赋值为nil而不是空字符串)。

然而,如果你看一下JSON(JavaScript对象表示法)的原始目标,你会注意到在JavaScript中几乎没有任何区别:

var obj = JSON.parse('{"first_name": null}');
alert(obj.first_name)

和:

var obj = JSON.parse('{}');
alert(obj.first_name)

换句话说:将null赋值给一个字段与根本不指定它具有相同的效果。大多数JSON解析器都是这样工作的。

不指定空字段是由Go JSON编组器支持的:

type MyType struct {
    firstname string `json:omitempty`
}

最终,这取决于你想要用你的JSON做什么 JSON marshall nullable type value in database/sql Go

英文:

If you really want to have null field, you will have to resort to a custom marshaller (or maybe, just maybe, use *string fields in struct and assign nil instead of an empty string).

However, if you look at the original goal of JSON (JavaScript Object Notation), you will notice that in JavaScript there is hardly any difference between:

var obj = JSON.parse('{"first_name": null }');
alert(obj.first_name)

and:

var obj = JSON.parse('{}');
alert(obj.first_name)

In other words: assigning null to a field has the same effect as not specifying it all. And most JSON parsers work like this.

Not specifying empty fields is supported by the Go JSON marshaller:

type MyType struct {
    firstname string `json:omitempty`
}

In the end, it depends on what you want to do with your JSON JSON marshall nullable type value in database/sql Go

huangapple
  • 本文由 发表于 2014年1月23日 07:07:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/21295972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定