亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

帶有令牌身份驗證的 Golang REST api 請求到 json 數組響應

帶有令牌身份驗證的 Golang REST api 請求到 json 數組響應

Go
偶然的你 2022-11-08 16:15:40
編輯這是工作代碼,以防有人發現它有用。這個問題的標題最初是“How to parse a list fo dicts in golang”。這是標題不正確,因為我引用了我在 python 中熟悉的術語。package mainimport (    "encoding/json"    "fmt"    "io/ioutil"    "log"    "net/http")//Regional Struttype Region []struct {    Region      string `json:"region"`    Description string `json:"Description"`    ID          int    `json:"Id"`    Name        string `json:"Name"`    Status      int    `json:"Status"`    Nodes       []struct {        NodeID    int    `json:"NodeId"`        Code      string `json:"Code"`        Continent string `json:"Continent"`        City      string `json:"City"`    } `json:"Nodes"`}//working request and responsefunc main() {    url := "https://api.geo.com"    // Create a Bearer string by appending string access token    var bearer = "TOK:" + "TOKEN"    // Create a new request using http    req, err := http.NewRequest("GET", url, nil)    // add authorization header to the req    req.Header.Add("Authorization", bearer)    //This is what the response from the API looks like    //regionJson := `[{"region":"GEO:ABC","Description":"ABCLand","Id":1,"Name":"ABCLand [GEO-ABC]","Status":1,"Nodes":[{"NodeId":17,"Code":"LAX","Continent":"North America","City":"Los Angeles"},{"NodeId":18,"Code":"LBC","Continent":"North America","City":"Long Beach"}]},{"region":"GEO:DEF","Description":"DEFLand","Id":2,"Name":"DEFLand","Status":1,"Nodes":[{"NodeId":15,"Code":"NRT","Continent":"Asia","City":"Narita"},{"NodeId":31,"Code":"TYO","Continent":"Asia","City":"Tokyo"}]}]`    //Send req using http Client    client := &http.Client{}    resp, err := client.Do(req)    if err != nil {        log.Println("Error on response.\n[ERROR] -", err)    }    defer resp.Body.Close()    body, err := ioutil.ReadAll(resp.Body)    if err != nil {        log.Println("Error while reading the response bytes:", err)    }    var regions []Region    json.Unmarshal([]byte(body), &regions)    fmt.Printf("Regions: %+v", regions)}
查看完整描述

1 回答

?
慕少森

TA貢獻2019條經驗 獲得超9個贊

看看這個操場上的例子以獲得一些指示。


這是代碼:


package main


import (

    "encoding/json"

    "log"

)


func main() {

    b := []byte(`

[

  {"key": "value", "key2": "value2"},

  {"key": "value", "key2": "value2"}

]`)


    var mm []map[string]string

    if err := json.Unmarshal(b, &mm); err != nil {

        log.Fatal(err)

    }


    for _, m := range mm {

        for k, v := range m {

            log.Printf("%s [%s]", k, v)

        }

    }

}

我重新格式化了您包含的 API 響應,因為它不是有效的 JSON。


在 Go 中,需要定義類型以匹配 JSON 模式。


我不知道為什么 API 會附加%到結果的末尾,所以我忽略了這一點。如果包含它,您將需要在解組之前從文件中修剪結果。


你從解組中得到的是一張地圖。然后,您可以遍歷切片以獲取每個映射,然后遍歷每個映射以提取keys 和 alues v。


更新

在您更新的問題中,您包含不同的 JSON 模式,并且此更改必須通過更新類型反映在 Go 代碼中。您的代碼中還有其他一些錯誤。根據我的評論,我鼓勵你花一些時間學習這門語言。


package main


import (

    "bytes"

    "encoding/json"

    "io/ioutil"

    "log"

)


// Response is a type that represents the API response

type Response []Record


// Record is a type that represents the individual records

// The name Record is arbitrary as it is unnamed in the response

// Golang supports struct tags to map the JSON properties

// e.g. JSON "region" maps to a Golang field "Region"

type Record struct {

    Region      string `json:"region"`

    Description string `json:"description"`

    ID          int    `json:"id"`

    Nodes       []Node

}

type Node struct {

    NodeID int    `json:"NodeId`

    Code   string `json:"Code"`

}


func main() {

    // A slice of byte representing your example response

    b := []byte(`[{

        "region": "GEO:ABC",

        "Description": "ABCLand",

        "Id": 1,

        "Name": "ABCLand [GEO-ABC]",

        "Status": 1,

        "Nodes": [{

            "NodeId": 17,

            "Code": "LAX",

            "Continent": "North America",

            "City": "Los Angeles"

        }, {

            "NodeId": 18,

            "Code": "LBC",

            "Continent": "North America",

            "City": "Long Beach"

        }]

    }, {

        "region": "GEO:DEF",

        "Description": "DEFLand",

        "Id": 2,

        "Name": "DEFLand",

        "Status": 1,

        "Nodes": [{

            "NodeId": 15,

            "Code": "NRT",

            "Continent": "Asia",

            "City": "Narita"

        }, {

            "NodeId": 31,

            "Code": "TYO",

            "Continent": "Asia",

            "City": "Tokyo"

        }]

    }]`)


    // To more closely match your code, create a Reader

    rdr := bytes.NewReader(b)


    // This matches your code, read from the Reader

    body, err := ioutil.ReadAll(rdr)

    if err != nil {

        // Use Printf to format strings

        log.Printf("Error while reading the response bytes\n%s", err)

    }


    // Initialize a variable of type Response

    resp := &Response{}

    // Try unmarshaling the body into it

    if err := json.Unmarshal(body, resp); err != nil {

        log.Fatal(err)

    }


    // Print the result

    log.Printf("%+v", resp)

}


查看完整回答
反對 回復 2022-11-08
  • 1 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號