登录
首页 >  Golang >  Go问答

使用Go对json进行操作

来源:stackoverflow

时间:2024-02-14 23:36:38 122浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《使用Go对json进行操作》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

嘿,刚刚开始将我的 python 代码转换为 go,但在 json 操作上遇到一些问题...这是我到目前为止的代码

package test

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
    "time"
)

type collection struct {
    contract string
}

type data struct {
    activity activity `json:"activity"`
}

type activity struct {
    activities activities `json:"activities"`
    hasmore    bool       `json:"hasmore"`
}

type activities []sale

type sale struct {
    from             string           `json:"from"`
    from_login       string           `json:"from_login"`
    to               string           `json:"to"`
    to_login         string           `json:"to_login"`
    transaction_hash string           `json:"transaction_hash"`
    timestamp        int              `json:"timestamp"`
    types            string           `json:"type"`
    price            float32          `json:"price"`
    quantity         string           `json:"quantity"`
    nft              nft              `json:"nft"`
    attributes       string           `json:"attributes"`
    collection       collectionstruct `json:"collection"`
}

type nft struct {
    name       string        `json:"name"`
    thumbnail  string        `json:"thumbnail"`
    asset_id   string        `json:"asset_id"`
    collection nftcollection `json:"collection"`
}

type nftcollection struct {
    avatar    string `json:"avatar"`
    name      string `json:"name"`
    certified bool   `json:"certified"`
}

type collectionstruct struct {
    avatar    string `json:"avatar"`
    address   string `json:"address"`
    name      string `json:"name"`
    certified bool   `json:"certified"`
}

func (c collection) getsales(filter, types string) []sale { // déclaration de ma méthode getsales() liée à ma structure collection
    client := &http.client{timeout: time.duration(1) * time.second}

    const url = "https://backend.api.io/query"

    // create a new request using http
    req, err := http.newrequest("post", url)
    if err != nil {
        panic(err)
    }

    // set header for the request
    req.header.set("content-type", "application/json")

    // send request
    res, err := client.do(req)
    if err != nil {
        panic(err)
    }

    defer res.body.close()
    content, err_ := ioutil.readall(res.body)
    if err_ != nil {
        panic(err_)
    }

    var resultjson data
    json.unmarshal(content, &resultjson)
    fmt.printf("%+v\n", resultjson)
    return resultjson.activity.activities.sale

}

我不明白为什么我的 sale 结构是空的:/我创建了所有这些结构以便使用 unmarshal,以便我可以循环。我检查返回的 json 的结构方式并复制它,我确信我错过了一些东西,但不知道是什么

编辑:我认为我有一些东西,实际上数组是“活动”而不是“销售”:

type Collection struct {
    Contract string
}

type Data struct {
    Activity Activity `json:"activity"`
}

type Activity struct {
    Activities Activities `json:"activities"`
    HasMore    bool       `json:"hasMore"`
}

type Activities []struct {
    Sale Sale //`json:"sale"`
}

type Sale struct {
    From             string           `json:"from"`
    From_login       string           `json:"from_login"`
    To               string           `json:"to"`
    To_login         string           `json:"to_login"`
    Transaction_hash string           `json:"transaction_hash"`
    Timestamp        int              `json:"timestamp"`
    Types            string           `json:"type"`
    Price            float32          `json:"price"`
    Quantity         string           `json:"quantity"`
    Nft              Nft              `json:"nft"`
    Attributes       string           `json:"attributes"`
    Collection       CollectionStruct `json:"collection"`
}

type Nft struct {
    Name       string        `json:"name"`
    Thumbnail  string        `json:"thumbnail"`
    Asset_id   string        `json:"asset_id"`
    Collection NftCollection `json:"collection"`
}

type NftCollection struct {
    Avatar    string `json:"avatar"`
    Name      string `json:"name"`
    Certified bool   `json:"certified"`
}

type CollectionStruct struct {
    Avatar    string `json:"avatar"`
    Address   string `json:"address"`
    Name      string `json:"name"`
    Certified bool   `json:"certified"`
}

但这一次它返回给我:{activity:{activities:[] hasmore:false}},其中“activity”值应该是一个 nft 结构数组


正确答案


添加@larsks的答案,我可以看到更多错误

  1. ioutil.readall 已返回一个字节数组,您可以直接将其用于解组。 json.unmarshal(content, &resultjson)

  2. 许多错误都会被忽略,因此如果遇到任何错误,执行都不会停止。

我建议按如下方式更改功能:

func (c collection) getsales(filter, types string) []sale {
    const url = "https://api.com/"

    req, err := http.newrequest("post", url, requestbody)
    if err != nil {
        panic(err)
    }
    
    res, err := http.defaultclient.do(req)
    if err != nil {
        panic(err)
    }

    defer res.body.close()
    content, err := ioutil.readall(res.body)
    if err != nil {
        panic(err)
    }

    var resultjson data
    err = json.unmarshal(content, &resultjson)
    if err != nil {
        panic(err)
    }

    fmt.printf("%+v\n", resultjson)
    return resultjson.activity.activities.sales
}

您编写的代码无法编译(由于几个未定义的变量),因此很难将功能问题与语法问题分开。

但是,有一点值得注意:您正在使用 req, err := http.newrequest(...) 创建 http 请求,但您从未使用客户端执行该请求。参见例如the documentation,其中包括以下示例:

client := &http.Client{
    CheckRedirect: redirectPolicyFunc,
}

resp, err := client.Get("http://example.com")
// ...

req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...

如果使用newrequest创建请求,则必须使用client.do(req)来执行它。

到这里,我们也就讲完了《使用Go对json进行操作》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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