duanbamo0127 2018-10-26 10:14
浏览 76
已采纳

如何构建复杂的go数据结构

I have the following data struct to build and send data in it. Then convert it to json and write a file. I need an array. Its element is a map. map["targets"] value is an array and map["labels"] is another map. How to build the complex data struct?

[
  {
    "targets": ["10.11.150.1:7870", "10.11.150.4:7870"],
    "labels": {
      "job": "mysql"
    }
  },
  {
    "targets": ["10.11.122.11:6001", "10.11.122.15:6002"],
    "labels": {
      "job": "postgres"
    }
  }
]

~

  • 写回答

2条回答 默认 最新

  • dongweng9474 2018-10-26 10:40
    关注

    So your struct would look like this:

    type Obj struct {
        Targets []string `json:"targets"`
        Labels map[string]string `json:"labels"`
    }
    

    Populate it:

    obj := []Obj{
        Obj{
            Targets: []string{"10.11.150.1:7870", "10.11.150.4:7870"},
            Labels: map[string]string{
                "job": "mysql",
            },
        },
        Obj{
            Targets: []string{"10.11.122.11:6001", "10.11.122.15:6002"},
            Labels: map[string]string{
                "job": "postgres",
            },
        },
    }
    

    Marshal it to a string:

    jsonBytes, err := json.Marshal(obj)
    if err != nil {
        log.Fatal("error marshaling struct to JSON:", err)
    }
    

    Write it to a file:

    if err := ioutil.WriteFile("output.json", jsonBytes, 0644); err != nil {
        log.Fatal("error writing file:", err)
    }
    

    Here’s everything all together:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "log"
    )
    
    type obj struct {
        Targets []string          `json:"targets"`
        Labels  map[string]string `json:"labels"`
    }
    
    func main() {
    
        obj := []obj{
            obj{
                Targets: []string{"10.11.150.1:7870", "10.11.150.4:7870"},
                Labels: map[string]string{
                    "job": "mysql",
                },
            },
            obj{
                Targets: []string{"10.11.122.11:6001", "10.11.122.15:6002"},
                Labels: map[string]string{
                    "job": "postgres",
                },
            },
        }
    
        jsonBytes, err := json.Marshal(obj)
        if err != nil {
            log.Fatal("error marshaling struct to JSON:", err)
        }
    
        if err := ioutil.WriteFile("output.json", jsonBytes, 0644); err != nil {
            log.Fatal("error writing file:", err)
        }
    
        fmt.Printf("%+v
    ", jsonBytes)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分