简体   繁体   English

将 API 请求拉入嵌套结构

[英]Pull API request into nested struct

I'm currently pulling an API response into a struct.我目前正在将 API 响应拉入结构中。

I'm fine with a normal response of say:我可以正常回答说:

  [ 
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
  ]

However when I get data like this:但是,当我得到这样的数据时:

  "urls": [
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
  ]

I cant seem to parse it to the struct.我似乎无法将其解析为结构。

It seems like a stupid question as its basically the same.这似乎是一个愚蠢的问题,因为它基本相同。

Here is what I am doing:这是我正在做的事情:

   type urls struct {
    Urls struct {
        Date   string `json:"date"`
        User   string `json:"user"`
        Urls   string `json:"urls"`
    } `json:"urls"`
   }

   type url []urls

and within the function:并在函数内:

   resp, err := http.Get("https://url")
   if err != nil {
        fmt.Println("No response from request")
   }
   defer resp.Body.Close()
   body, err := ioutil.ReadAll(resp.Body) // response body is []byte
   var u url
   _ = json.Unmarshal(body, &u)

Unfortunately this isnt working and u is empty.不幸的是,这不起作用,你是空的。

With the first response I can have a struct like this and it works fine:有了第一个响应,我可以有一个这样的结构,它工作正常:

  type urls struct {
       Date   string `json:"date"`
       User   string `json:"user"`
       Urls   string `json:"urls"`
  }

I think what I'm trying to say is a combination of the above and plus a little bit of my experience.我想我想说的是上面的结合,再加上我的一点经验。

  1. Your Urls field is an array in JSON, but not in the struct you declared.您的 Urls 字段是 JSON 中的数组,但不在您声明的结构中。
  2. You should not ignore the error returned by json.Unmarshal(body, &u) .您不应忽略 json.Unmarshal(body, &u) 返回的错误。
  3. The Json you posted is not grammatically correct.您发布的 Json 在语法上不正确。 I modified your Json string slightly, it could be:我稍微修改了你的 Json 字符串,它可能是:
{
"urls": [
    {"date":"2021-10-04","user":"Test","url":"Anonymous"},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"}
  ]
}

And to Go struct should be:而去结构应该是:

type URL struct {
    SubURLs []struct {
        Date string `json:"date"`
        User string `json:"user"`
        URL  string `json:"url"`
    } `json:"urls"`
}

Next, I introduce you to one possible way when you are dealing with JSON to Go structs: You can paste your Json on this website , and then you can get its corresponding Go structure, and you can also correct your Json by the way.接下来给大家介绍一种处理 JSON to Go structs 的可能方式:你可以把你的 Json 粘贴到这个网站上,然后就可以得到它对应的 Go 结构体,顺便也可以修正你的 Json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM