首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >去json操纵

去json操纵
EN

Stack Overflow用户
提问于 2022-08-27 22:31:50
回答 2查看 65关注 0票数 1

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

代码语言:javascript
复制
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结构是空的:/我创建了所有这些结构,以便使用解组,这样我就可以循环。我检查返回的json的结构和复制方式,我确定我遗漏了一些东西,但不知道是什么

编辑:我想我有一些东西,实际上数组是活动而不是Sale:

代码语言:javascript
复制
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}},其中的活动值应该是Nft的数组。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-08-28 03:46:17

除了@larsks的答案之外,我还可以看到更多的错误。

  1. ioutil.ReadAll已经返回一个字节数组,可以直接用于非编组。json.Unmarshal(content, &resultJson)
  2. 许多错误被忽略,因此如果遇到任何错误,执行就不会停止。

我建议将这一职能修改如下:

代码语言:javascript
复制
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
}
票数 0
EN

Stack Overflow用户

发布于 2022-08-27 23:02:03

编写的代码不会编译(因为有几个未定义的变量),因此很难将函数问题与语法问题分开。

然而,有一点很突出:您使用req, err := http.NewRequest(...)创建了一个HTTP请求,但是您从未使用客户端执行请求。参见例如文献资料,其中包括以下示例:

代码语言:javascript
复制
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)来执行请求。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73514820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档