【问题标题】:How to convert map of map of interface to string如何将接口映射的映射转换为字符串
【发布时间】:2019-09-21 22:17:51
【问题描述】:

我是新来的 lang,我有一种变量,如下所示:

type ResultData map[string]map[string][]interface{}

当我在这个变量中接收数据时,如何在 Go 中将整个数据转换为单个字符串?

【问题讨论】:

    标签: go


    【解决方案1】:

    你可以使用类似Sprintf:

    func main() {
        d1 := map[string][]interface{}{
            "a": []interface{}{20, "hello"},
            "b": []interface{}{100}}
        d2 := map[string][]interface{}{
            "x": []interface{}{"str", 10, 20},
        }
    
        m := make(map[string]map[string][]interface{})
        m["d1"] = d1
        m["d2"] = d2
    
        s := fmt.Sprintf("%v", m)
        fmt.Println(s)
    }
    

    或者您也可以使用json 模块来转换为带有json.Marshal 的JSON 字符串。如果interface{} 背后的实际运行时类型可以编组为 JSON,json.Marshal 将自行解决。

    b, _ := json.Marshal(m)
    fmt.Println(string(b))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 2019-06-14
      相关资源
      最近更新 更多