gpt4 book ai didi

go - 从链接读取JSON

转载 作者:行者123 更新时间:2023-12-03 10:10:18 26 4
gpt4 key购买 nike

我想返回从此link返回的字符串,并基于返回的数据构建一个JSON对象,我编写了以下代码来读取url并正确获取该字符串,但是它无法构建JSON对象,并且没有返回任何东西!

package main

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

type Product struct {
ProductId string `json:"id"`
ProductName string `json:"description"`
}

func main() {
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()

htmlData, err := ioutil.ReadAll(resp.Body) //<--- here!

if err != nil {
fmt.Println(err)
os.Exit(1)
}

// print out
fmt.Println(string(htmlData))

var product Product
json.Unmarshal([]byte(string(htmlData)), &product)

fmt.Printf("ID: %s, Description: %s", product.ProductId, product.ProductName)
}
输出:
{"user":[{"ProductId":1,"ProductName":"Helmet"},{"ProductId":2,"ProductName":"Glove"},{"ProductId":3,"ProductName":"Detecttor"}]}
ID: , Description:

最佳答案

1-解码目标结构必须与数据匹配,

type Data struct {
User []Product `json:"user"`
}
2-字段类型应该匹配,因此 ProductID应该是 uint3-输出的json OP应该匹配使用的标签, json:"id"应该替换为 json:"ProductId"description
type Product struct {
ProductId uint `json:"ProductId"`
ProductName string `json:"ProductName"`
}
因此,一个有效的代码是:
package main

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

type Data struct {
User []Product `json:"user"`
}
type Product struct {
ProductId uint `json:"ProductId"`
ProductName string `json:"ProductName"`
}

func main() {
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()

htmlData, err := ioutil.ReadAll(resp.Body)

if err != nil {
fmt.Println(err)
os.Exit(1)
}

// print out
fmt.Println(string(htmlData))

//var product Product
var data Data
json.Unmarshal([]byte(string(htmlData)), &data)

fmt.Println(data)
fmt.Println(data.User)
fmt.Println(data.User[0])
fmt.Printf("id: %v, description: %s", data.User[0].ProductId, data.User[0].ProductName)
}

关于go - 从链接读取JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64429436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com