【问题标题】:Unable to parse Golang map and nested json无法解析 Golang 地图和嵌套 json
【发布时间】:2022-01-12 12:34:51
【问题描述】:

我有下面的sn-p



func fakeGetInclusterConfig() (*corev1.ConfigMap, error) {
        configMap := &corev1.ConfigMap{
                Data: map[string]map[string]string{"cluster-config.json":{
                        "cluster_id":"xxx",
                        "cluster_name":"yyy",
                        "cluster_type":"zzz",
                        "cluster_pay_tier":"paid",
                },
                },
        }
        return configMap, nil
}

但是Data 部分有一些问题。我无法正确声明类型。我尝试了所有我知道的选项,但显然不是正确的选项。请在这里有人帮忙

主要代码期望

        configmap, err := cm.GetConfigMap(handler.k8sclient, Configmap, ConfigmapNS)
        clusterConfigJSON := configmap.Data["cluster-config.json"]
        clusterConfigJSON = strings.Replace(clusterConfigJSON, "\n", "", -1)
        clusterConfigJSON = strings.Replace(clusterConfigJSON, " ", "", -1)
        var clusterConfigInfo clusterInfo
        err = json.Unmarshal([]byte(clusterConfigJSON), &clusterConfigInfo)
        if err != nil {

所以我想要一个 cluster-config.json 键的 json 结构。我正在尝试为测试用例创建虚拟数据。

【问题讨论】:

  • 什么是corev1.ConfigMap
  • ConfigMap.Data 是一个“简单的”map[string]string,而不是地图的地图。这样做:&corev1.ConfigMap{Data: map[string]string{"cluster_id":"xxx"}}
  • 但是我必须有一个json来解析细节。我已经添加了更多有问题的细节。
  • 配置映射中的值只是字符串;将Data 视为map[string]string 以外的任何内容是不正确的。如果需要将结构化数据转储为值,则需要对其进行 JSON 编码。

标签: go go-map


【解决方案1】:

我可以这样解决它

clusterDetails := `{"cluster_id":"xxx","cluster_name":"yyy","cluster_type":"kkk","cluster_pay_tier":"paid","datacenter": "dal","account_id": "mmm","created": "2021-11-23T07:18:25+0000","name": "tokreleasetest","master_public_url": "https://xxx.containers.cloud.nnn.com:1111","master_url": "https://c106.dal-tok.containers.cloud.nnn.com:1111","crn":  "crn:v1:bluemix:public:containers-kubernetes:dal-tok:2334445:cdfr343"}`
        configMap := &corev1.ConfigMap{
                Data: map[string]string{"cluster-config.json":clusterDetails},
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2018-12-21
    • 2013-07-09
    • 1970-01-01
    • 2020-12-08
    • 2021-02-15
    • 1970-01-01
    相关资源
    最近更新 更多