英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论