将struct数组转换为字符串数组以显示为表

问题描述 投票:2回答:1

我正在看下面的包:https://github.com/olekukonko/tablewriter

我想尝试打印我的结构,就像那样,但我无法将我的结构数组转换为包需要的字符串数组。

所以我尝试了类似的东西:

func print(quakes []Quake) {
    var data [][]string

    for _, quake := range quakes {
        b, err := json.Marshal(quake)
        append(data, []string(b))
    }

    table := tablewriter.NewWriter(os.Stdout)
    table.SetHeader([]string{"Name", "Sign", "Rating"})

    for _, v := range newData {
        table.Append(v)
    }
    table.Render() // Send output
}

我的地震结构:

type Quake struct {
    Googlemapref string `json:"googlemapref"`
    Segree       string `json: "degree"`
    DataUpdate   string `json: "dataUpdate"`
    MagType      string `json:"magType"`
    ObsRegion    string `json: "obsRegion"`
    Lon          string `json:"lon"`
    Source       string `json: "source"`
    Depth        int    `json:"depth"`
    TensorRef    string `json:"tensorRef"`
    Sensed       string `json:"sensed"`
    Shakemapid   string `json:"shakemapid"`
    Time         string `json:"time"`
    Lat          string `json:"lat"`
    Shakemapref  string `json:"shakemapref"`
    Local        string `json:"local"`
    Magnitud     string `json: "magnitud"`
}

感谢一些帮助,因为我是这门语言的新手,非常感谢

arrays go slice
1个回答
0
投票

您的代码存在一些问题。首先,append函数没有附加到位,所以你做append(data, []string(b))的结果被抛弃,所以我认为你想做data = append(data, []string(b))而不是。

此外,在结构上执行json.Marshal不会产生一些你尝试使用它的字符串。相反,它将生成一个包含所有值的字符串,例如{"googlemapref":"something","depth":10}。您要使用的表格编写器需要将一片值放入与标题匹配的表格中(您使用"Name", "Sign", "Rating"的示例标题)。

您可以使用像reflect那样的json包填充每行中的字段,但我认为这将比它的价值更复杂,您最好通过调用相关字段填写每一行:

func print(quakes []Quake) {
    var data [][]string

    for _, quake := range quakes {
        row := []string{quake.Googlemapref, quake.Segree, strconv.Itoa(quake.Depth),...}
        data = append(data, row)
    }

    table := tablewriter.NewWriter(os.Stdout)
    table.SetHeader([]string{"googlemapref", "degree", "depth",...})

    for _, v := range newData {
        table.Append(v)
    }
    table.Render() // Send output
}

(我已经离开了...让你自己填写其他字段,但包括深度以显示如何将其转换为字符串)。

© www.soinside.com 2019 - 2024. All rights reserved.