How properly append string map into json

hi all

I have config

{
  "sites": [
{
  "http://site1.info": 0
},
{
  "https://site2.info": 0
},
{
  "https://site3.info": 0
}
],
"time": 5
}

and struct

SiteList struct {
	Sites []map[string]int `json:"sites,omitempty"`
	Time  int `json:"time,omitempty"`
}

how I can append into my json file or delete one site and int?

1 Like

Be aware that Sites is a slice of map. So

  1. Creates a new map
    var m = make(map[string]int)
    m[“https://3.info:”] = 3

  2. Add this map to the slice
    siteList.Sites = append(siteList.Sites, m)

  3. To remove an item, just procede as you do when removing an element from a slice

func RemoveIndex(s []map[string]int, index int) []int {
    return append(s[:index], s[index+1:]...)
}

4) To update your file just writes the new json structure to it
file, _ := json.Marshal(siteList)
_ = ioutil.WriteFile("data.json", file, 0644)
2 Likes

thanks man for the help!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.