Removing a specific element from a json array in golang

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

Removing a specific element from a json array in golang

问题

我尝试了几个选项,但没有结果。如果有人知道某种解决方案,那就太好了。我试过使用 buger/jsonparser,因为它的解析速度很快。假设我想排除 object3 并将其赋值给 MYVARIABLE。

例如:

data:=[{object1}, {object2}, {object3}]

// 这个函数遍历数组
jsonparser.ArrayEach(data, func(key []byte, dataType jsonparser.ValueType, offset int, err error) {

    MYVARIABLE:=key

    return
})
英文:

I tried a few options but with no results. If anyone knows some kind of solution it would be nice. I was trying with buger/jsonparser because of the parsing speed. Lets say i want to exclude object3 and assign it to MYVARIABLE

for exaple :

data:=[{object1}, {object2}, {object3}]

//this function iterates through the array
jsonparser.ArrayEach(data, func(key []byte, dataType jsonparser.ValueType, offset int, err error) {

    MYVARIABLE:=key

	return
})

答案1

得分: 1

假设你已经成功将数据解析为结构体。你会有一个名为[]yourStruct的结构体数组,并且可以像这样将第三个元素赋值为空结构体:

yourStruct[2] = YourStruct{}

第三个元素仍然存在,但其值为空。不幸的是,在Go语言中,你不能将结构体赋值为nil值。

或者,你可以将包含JSON数据的[]byte转换为string,并迭代其中的元素,将其替换为空字符,但这种方法效率较低。

正如Kaedys所说,你可以使用切片来删除结构体数组中的元素,像这样:

yourStruct = yourStruct[:2]
fmt.Printf("result struct = %+v\n", yourStruct)
英文:

Let's say that you have successfully parsed your data to struct.
And you would have an array of yourStruct []yourStruct, and assign the third element with empty struct like this :

yourStruct[2] = YourStruct{}

the third element is still there with empty value. And unfortunately in go you can't assign struct with nil value.

or you can convert the []byte of your data that has your json to string and iterate it over to the their element and remove it with empty char, but this would be an expensive approach.

As Kaedys said you can remove your array struct using slice like this :

yourStruct = yourStruct[:2]
fmt.Printf("resutl struct = %+v\n", yourStruct)

huangapple
  • 本文由 发表于 2017年1月27日 19:36:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/41893086.html
匿名

发表评论

匿名网友

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

确定