如何在Golang中将null值插入JSON类型中

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

How to insert null value in JSON type in golang

问题

我已经为某些目的创建了远程模式,我必须插入一个像这样的 JSON 值:

"convert_to_money": {"IDR":10000},

我创建了一个这样的变异字段:

"convert_to_money": {
 Type: scalar.JSON,
},

解析器如下:

Convert_to_money := p.Args["convert_to_money"].(map[string]interface{})

结构体如下:

type TimeOvertimePolicy struct {
	ConvertToMoney JSONB
}

处理程序如下:

func UpdateOvertimesPolicy(Convert_to_money model.JSONB) (res gqltypes.SuccessType, err error) {
  timeOvertimesPolicy := model.TimeOvertimePolicy{
	ConvertToMoney: Convert_to_money,
  }

  err = pg.DB.Transaction(func(tx *gorm.DB) error {
    d := tx.Create(&timeOvertimesPolicy)
  }
}

我该如何为这种情况输入空值?

当前正在运行的情况下,如果变量为空,我必须插入一个变量 convert_to_money: {}

如果变量为空,我希望能够像这样插入变量:

"convert_to_money": null
英文:

i have create remote schema for some purpose i have to insert a json value like this

"convert_to_money": {"IDR":10000},

i create a mutation field like this

"convert_to_money": {
 Type: scalar.JSON,
},

resolver like this :

Convert_to_money := p.Args["convert_to_money"].(map[string]interface{})

struct like this :

type TimeOvertimePolicy struct {
	ConvertToMoney 			JSONB
}

and handler like this :

func UpdateOvertimesPolicy(Convert_to_money model.JSONB) (res gqltypes.SuccessType, err error) {
  timeOvertimesPolicy := model.TimeOvertimePolicy{
		ConvertToMoney: 		Convert_to_money,
	}

  err = pg.DB.Transaction(func(tx *gorm.DB) error {
    d := tx.Create(&timeOvertimesPolicy)
  }
}

How can i do input null value for case like this?

Which is running now I have to insert a variable "convert_to_money": {} like this if the variable is null

I wish i can insert variable like this if null

"convert_to_money": null

答案1

得分: 1

go语言中,指针类型存在nil(空)值。因此,如果你想插入一个nil值,那么你的Convert_to_money函数应该是指针类型。

英文:

In go nil (null) exist for pointers. So if you want to insert a nil value then your Convert_to_money should be of a pointer type.

答案2

得分: 0

你可以像这样插入变量:

"convert_to_money": nil
英文:

You can insert vairable like this

"convert_to_money": nil

答案3

得分: 0

如果你正在使用gorm,你可以使用pgtype.JSONB来初始化一个"null"值:

pgtype.JSONB{Status: pgtype.Null}

英文:

If you're using gorm, you can use pgtype.JSONB to init a "null" value:

> pgtype.JSONB{Status: pgtype.Null}

huangapple
  • 本文由 发表于 2021年7月14日 11:24:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/68371628.html
匿名

发表评论

匿名网友

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

确定