Konstantin Gvencadze
Konstantin Gvencadze

Reputation: 13

How to delete element from JSON array without deleting next elements in Golang

I have function that get ID from POST request and deleting element with number equal to ID with similar code:

w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding")

switch r.Method {
case "POST":
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Print(err)
        return
    }

    type row struct {
        Row int
    }
    var rowId row
    json.Unmarshal(body, &rowId)

    var id = rowId.Row
    type requestBody struct {
        Name        string
        Id          int
        Price       int
        Img         string
        Link        string
        Description string
    }
    var request requestBody
    json.Unmarshal([]byte(body), &request)

    file, _ := ioutil.ReadFile("./static/nuts.json")

    data := []requestBody{}

    json.Unmarshal(file, &data)
    data = append(data[:id])

    dataBytes, err := json.MarshalIndent(data, "", "   ")
    if err != nil {
        fmt.Print(err)
    }

    err = ioutil.WriteFile("./static/nuts.json", dataBytes, 0644)
    if err != nil {
        fmt.Print(err)
    }
}

But if I have 3 elements in JSON, and delete 2nd element, next element will delete to. I'm new to GO, and I don't know how to fix this problem. Help me pls

Upvotes: 0

Views: 754

Answers (1)

Konstantin Gvencadze
Konstantin Gvencadze

Reputation: 13

Answer was change this:

data = append(data[:id])

to this:

data = append(data[:id], data[id+1:]...)

And everything will work

Upvotes: 1

Related Questions