I want to get all the rows from the Google sheets API. It returns the data with the type[][]interface{}
.
My struct is
type Record struct {
Name string `json:"firstname"`
Mobile string `json:"mobile"`
}
I would like to put all the rows in a slice of struct []Record
where each field is a cell in the excel sheet.
Please see the code below for my attempt:
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
srv err := InitialiseSheets()
fmt.Println("")
if err != nil {
log.Fatalf("Unable to retrieve data from sheet: %v", err)
}
spreadsheetId := "1VoMAKHSnB6nptPnQqabMlKWraxWolYgPBxRo-thwmgk"
readRange := "A:B"
resp, err := srv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()
if err != nil {
log.Fatalf("Unable to retrieve data from sheet: %v", err)
}
var records []Record = make([]Record, len(resp.Values))
byt, err := resp.MarshalJSON()
var dat map[string]interface{}
if err = json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
for key, value := range dat {
switch key {
case "values":
switch vv := value.(type) {
case []interface{}:
for i, u := range vv {
switch r := u.(type) {
case interface{}:
records[i].Name = r.([]interface{})[0].(string)
records[i].Mobile = r.([]interface{})[1].(string)
// [Daniel Webster 425255565]
fmt.Println("kk.([]interface{})", r.([]interface{}))
// [Daniel Webster]
fmt.Println("kk.([]interface{})[0]", r.([]interface{})[0])
}
}
}
}
}
}
I'm sure doing something like records[i].Mobile = r.([]interface{})[1].(string)
isn't a proper way to do it, not sure how I even came up with it. Whats the best way in Go to do what I'm trying to achieve?
If you would like to run this code please setup authentication first by following: https://developers.google.com/sheets/api/quickstart/go and you can copy/paste my code.