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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试