I was watching the following package: https://github.com/olekukonko/tablewriter
And I want to try to print my struct as something like that, but I couldn't covert my array of structs into the array of strings that the package needs.
So I tried something like that:
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
}
My Quake Struct:
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"`
}
Would appreciate some help since I am new in the laguage, thanks a lot
There are a few issues with your code. Firstly, the append
function doesn't append in place so where you do append(data, []string(b))
the result is thrown away so I think you want to do data = append(data, []string(b))
instead.
Also, doing a json.Marshal
on the struct will not make a slice of strings which you try to use it as. Instead, it will produce a single string that has all of the values in such as {"googlemapref":"something","depth":10}
. The tablewriter you want to use expects to take a slice of values to put in the table that match the headings (where you appear to using the example headings of "Name", "Sign", "Rating"
.
You could use the reflect
package like json
does to populate the fields in each row but I think this would be more complexity than it is worth and you are better just filling in each row by calling the relevant fields:
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
}
(I've left the ...
for you to fill in the other fields yourself but included depth to show how to convert it to a string).