-2

How would I get this little program to work? I'm trying to read a bunch of cookies from a json string into a map and print the map. The below program prints nothing.

type htmlDoc struct {
    cookies map[string] string `json:"Cookies"`
}

func main() {
    jsonString := `{    Cookies: {
        ["name1": "Value1"],
        ["name2": "Value2"],
        ["name3": "Value3"]
    }}`

    var doc htmlDoc
    json.Unmarshal([]byte(jsonString), &doc)

    for name, value := range doc.cookies {
        fmt.Printf("%s\t%s\n", name, value)
    }
}
user2443447
  • 151
  • 1
  • 8

2 Answers2

1

There are some errors in your code, first your json is invalid, I believe the expected JSON is:

{"Cookies": [
    {"name1": "Value1"},
    {"name2": "Value2"},
    {"name3": "Value3"}]
}

Also, as md2perpe commented, you have to export Cookies from htmlDoc. Another matter, if Cookies is an array of maps, the htmlDoc must have the following structure

type htmlDoc struct {
    Cookies []map[string]string `json:"Cookies"`
}

And the main func

func main() {
    jsonString := `{"Cookies": [
        {"name1": "Value1"},
        {"name2": "Value2"},
        {"name3": "Value3"}]}`

    var doc htmlDoc
    json.Unmarshal([]byte(jsonString), &doc)

    for _, value := range doc.Cookies {
        for k, v := range value {
            fmt.Printf("%s\t%s\n", k, v)
        }
    }
}
Motakjuq
  • 2,199
  • 1
  • 11
  • 23
0

The field cookies need to be exported, i.e. be upper case:

type htmlDoc struct {
    Cookies map[string] string `json:"Cookies"`
}
md2perpe
  • 3,372
  • 2
  • 18
  • 22