我正在观看以下包裹: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
}
我的 Quake 结构:
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"`
}
非常感谢一些帮助,因为我是语言方面的新手,非常感谢
最佳答案
您的代码存在一些问题。首先,append
函数没有在适当的位置追加,所以在你执行 append(data, []string(b))
的地方,结果被丢弃了,所以我想你想要改为执行 data = append(data, []string(b))
。
此外,在结构上执行 json.Marshal
不会生成您尝试将其用作的字符串片段。相反,它将生成一个包含所有值的字符串,例如 {"googlemapref":"something","depth":10}
。您要使用的 tablewriter 需要将一部分值放入与标题匹配的表中(您似乎在使用 "Name"、"Sign"、"Rating"的示例标题
.
您可以像json
那样使用reflect
包来填充每一行中的字段,但我认为这会比它更复杂是值得的,你最好通过调用相关字段来填写每一行:
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
}
(我已将 ...
留给您自己填写其他字段,但包括深度以显示如何将其转换为字符串)。
关于arrays - 将结构数组转换为字符串数组以显示为表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55199826/