登录
首页 >  Golang >  Go问答

Google Sheet 数据转 json

来源:stackoverflow

时间:2024-04-02 14:00:33 206浏览 收藏

大家好,我们又见面了啊~本文《Google Sheet 数据转 json》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我在 Google Sheets 上有以下示例数据,有没有办法将 Google Apps 脚本与 Go Lang 结合起来,以便我可以在 GO 应用中将工作表数据作为 Json 处理?


解决方案


是的,有:

1- 在 google 云端硬盘中,创建新的脚本表并编写如下代码:

function doget(){
  // open google sheet using id
  var ss = spreadsheetapp.openbyid("1eldczogyctqxgqmc5qulz4thcnksiodkljoyc762ctk");
  var sheet = ss.getsheetbyname("master");
  // read all data rows from google sheet
  const values = sheet.getrange(2, 1, sheet.getlastrow() - 1, sheet.getlastcolumn()).getvalues();
  // converts data rows in json format
  const result = json.stringify(values.map(([a,b]) => ({productid: a,productname:b,})));
  // returns result
  return contentservice.createtextoutput(result).setmimetype(contentservice.mimetype.json);
}

发布脚本,第一次发布时可能会要求您进行授权,因此您需要接受(注意:每次更改时,您都必须以另一个版本号发布)

设置对任何人的访问权限,甚至是匿名的。并部署。

使用您的 google 帐户登录。选择下面不安全的选项。

允许获取您的网络应用 api 的 url。

2- 在 go lang 中,使用之前发布步骤生成的链接编写以下代码:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)

type product struct {
    productid   uint   `json:"productid"`
    productname string `json:"productname"`
}

func main() {
    // read the returned response
    url := "https://script.googleusercontent.com/macros/echo?user_content_key=wbsjpdnsn6x1fcyexsr6tdadval0vdvmsommxfhgbt5sfk0ia80dp7kpd27glpzbyz8vrwfdiueci2ogmjetgfl5o8da25t1m5_bxdlh2jw0nuo2odemn9ccs2h10ox_1xsncgqajx_ryfhecjzengb6k9xagtox6m1tiig811crpk9nxl8zks7ujtno1dvqxme1kqfaj8wxssklor-eqzombnrgq-tk&lib=m0b6gxyh0eoymkp7qr1xy9xw8gujxfqgh"
    resp, err := http.get(url)
    if err != nil {
        log.fatal(err)
    }

    defer resp.body.close()

    // read the body of the response
    htmldata, err := ioutil.readall(resp.body)

    if err != nil {
        fmt.println(err)
        os.exit(1)
    }

    // print out
    fmt.println(string(htmldata)) // the data is returned as []byte, so string required to display it correctly

    // unmarshall the returned []byte into json
    var products []product
    json.unmarshal([]byte(htmldata), &products)
    fmt.printf("id: %v, description: %s", products[0].productid, products[0].productname)
}

运行上面的脚本,你会得到:

PS D:\> go run gsheet.go
[{"ProductId":1,"ProductName":"Helmet"},{"ProductId":2,"ProductName":"Glove"},{"ProductId":3,"ProductName":"Detecttor"}]
id: 1, description: Helmet

注释:

在go代码中,需要保证以下几点: 1-解组目标结构必须与数据匹配 2-字段类型应该匹配,例如 productid 应该是 uint 如果定义为 string 将失败 3- 输出中获得的 json op 应与使用的标签匹配,例如,使用 json:"id" 而不是 json:"productid" for productid 将失败

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>