Home > Back-end >  How to delete the key value pair using golang
How to delete the key value pair using golang

Time:06-11

How we can convert the following JSON data:

{
  "id": 1,
  "doo": [
    {
      "foo": 7,
      "boo": [
        {
          "a": "201",
          "b": [
            {
              "c": "110",
              "d": "io",
              "e": 56
            }
          ]
        }
      ],
      "moo": 0
    }
  ]
}

to the following JSON data set

{
  "id": 1,
  "doo": [
    {
      "foo": 7,
      "moo": 0
    }
  ]
}

So, I have to remove the nested JSON key-value i.e., boo

So, I want to write the function in golang to achieve this. Please help!

CodePudding user response:

In Go, the preferred approach would be to model your input document as a struct with only the fields you care about. Then you can "Unmarshal" (parse) the input JSON into memory as your struct and then "Marshal" (stringify) your struct from memory into a string which you can print. Since the struct contains only the fields you care about they will be the only ones printed.

For example (Go playground):

type Doc struct {
    ID   int `json:"id"`
    Doos []struct {
        Foo int `json:"foo"`
        Moo int `json:"moo"`
    } `json:"doo"`
}

var doc Doc

// Parse the input JSON string into a "Doc", thus ignoring unwanted fields.
if err := json.Unmarshal([]byte(inputstr), &doc); err != nil {
    panic(err)
}

// Now print the "Doc" as JSON to generate a string with only the desired fields.
if bs, err := json.MarshalIndent(doc, "", "  "); err != nil {
    panic(err)
} else {
    fmt.Println(string(bs))
    // {
    //   "id": 1,
    //   "doo": [
    //     {
    //       "foo": 7,
    //       "moo": 0
    //     }
    //   ]
    // }
}

CodePudding user response:

Unmarshal the JSON document to map[string]any. Dig through the resulting Go values to find the map with the key to delete. Delete the key. Marshal back to JSON.

var v map[string]any
if err := json.Unmarshal([]byte(doc), &v); err != nil {
    log.Fatal(err)
}

// if the doo field is a slice ...
if v, ok := v["doo"].([]any); ok {
    // for each slice element ...
    for _, v := range v {
        // if the slice element is a map ...
        if v, ok := v.(map[string]any); ok {
            // delete the key from the map
            delete(v, "boo")
        }
    }
}

p, _ := json.Marshal(v) // p is the result

Run the program on the GoLang PlayGround.

The advantage of this approach is that it retains all entities in the JSON document except of the ones you want to delete. Unmarshalling the document to concrete Go types (structs, etc) and marshaling those values back to JSON will delete all entities in the document not explicitly mentioned in the Go types.

  • Related