解组 JSON 到映射结构

Unmarshal JSON to Struct of Map

我有以下程序。我需要将 JSON 数据转换为包含单个 map[string]string 类型字段的对象类型缓存。我做错了什么 w.r.t。正在初始化映射和解组 JSON 但无法识别语法问题。

注意:为了方便起见,我整理了数据以获得示例 JSON 数据。

package main

import (
    "fmt"
    "encoding/json"
    "strconv"
)

const data = `{"Mode":{"ID-1":"ON","ID-2":"OFF","ID-3":"ON"}}`

type Cache struct {
    Mode map[string]string `json:"Mode"`
}

func main() {
    jsonData, _ := json.Marshal(data)
    fmt.Println(strconv.Unquote(string(jsonData)))

    var c Cache
    c.Mode = make(map[string]string) //I want to initialise map so that I can store data in next step, but this is wrong I know
    c.Mode["ID-4"] = "ON" //Want to store data like this
    
    json.Unmarshal(jsonData, &c) 
    fmt.Println(c) //I am getting output as nil map i.e. {map[]}
    for k, v := range c.Mode {
        fmt.Println(k, v) //I am getting NO output i.e. blank
    }
}

这是您修复的代码https://play.golang.org/p/5ftaiz_Q5wl(附上副本)

package main
import (
    "encoding/json"
    "fmt"
    "log"
)

const data = `{"Mode":{"ID-1":"ON","ID-2":"OFF","ID-3":"ON"}}`

type Cache struct {
    Mode map[string]string `json:"Mode"`
}

func main() {
    c := Cache{}
    err := json.Unmarshal([]byte(data), &c)
    if err != nil {
        log.Println(err)
    }
    c.Mode["ID-4"] = "ON" //Want to store data like this

    fmt.Println(c) 
    for k, v := range c.Mode {
        fmt.Println(k, v) 
    }
}

这是输出:

{map[ID-1:ON ID-2:OFF ID-3:ON ID-4:ON]}
ID-2 OFF
ID-3 ON
ID-4 ON
ID-1 ON