Zozo
Zozo

Reputation: 183

Removing a specific element from a json array in golang

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

Upvotes: 1

Views: 2044

Answers (1)

Gujarat Santana
Gujarat Santana

Reputation: 10564

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)

Upvotes: 1

Related Questions