dqfr90979
2017-01-27 11:36
浏览 853

从Golang中的json数组中删除特定元素

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
})

图片转代码服务由CSDN问答提供 功能建议

我尝试了一些选项,但没有结果。 如果有人知道某种解决方案,那就太好了。 由于解析速度过快,我尝试使用 buger / jsonparser 。 假设我想排除object3并将其分配给MYVARIABLE

例如:

  data:= [{{object1},{object2  },{object3}] 
 
 //此函数遍历数组
jsonparser.ArrayEach(data,func(key [] byte,dataType jsonparser.ValueType,offset int,err error){
 
 MYVARIABLE:  = key 
 
 return 
})
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongtan1845 2017-01-27 13:35
    已采纳

    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
    ", yourStruct)
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题