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

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

例如:</ p>

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

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

MYVARIABLE: = key

return
})
</ code> </ pre>
</ div>

展开原文

原文

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

doumaikuang4202
doumaikuang4202 请添加一些代码作为示例。
3 年多之前 回复

1个回答



假设您已成功将数据解析为struct。
您将拥有一个您的结构数组 [] yourStruct < / code>,并为第三个元素分配空结构,如下所示:</ p>

  yourStruct [2] = YourStruct {} 
</ code> </ pre>
\ n

第三个元素仍然在那里,值为空。 不幸的是,您不能使用 nil </ code>值分配结构。 </ p>

,或者您可以将具有json的数据的 [] byte </ code>转换为 string </ code>并将其迭代到其元素 并使用空字符将其删除,但这将是一种昂贵的方法。</ p>

作为 Kaedys </ a>说您可以使用像这样的切片来删除数组结构:</ p>

  yourStruct = yourStruct [:2] 
fmt.Printf(“ resutl struct =%+ v
” ,yourStruct)
</ code> </ pre>
</ div>

展开原文

原文

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)

dongrou5254
dongrou5254 是的,你很棒,这是正确的
3 年多之前 回复
dongmouhao7438
dongmouhao7438 您可以轻松地从切片中省略条目。 yourStruct = append(yourStruct [:2],yourStruct [3:] ...)。 只要切片的长度为3或更大,就不会惊慌(即使长度3的切片中的索引3是无效的索引,运行时也会进行编码以正确处理它)。
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐