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

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

如何發送動態 json 鍵/值作為請求參數

如何發送動態 json 鍵/值作為請求參數

Go
大話西游666 2023-03-29 17:14:37
package mainimport (    "strings"    "net/http"    "encoding/json"    "fmt")func main() {    j := `{"url":"http://localhost/test/take-request", "params":{"name":"John","age":"20"},"type":"get"}`    // k := `{"url":"http://localhost/test/take-request", "params":{"gender":"m","a":"20"},"type":"post"}`    request := map[string]interface{}{}    err := json.Unmarshal([]byte(j), &request)    if err != nil {        panic(err)    }    fmt.Println(request)    requestType = strings.ToUpper(request["type"]);    requestUrl = request["url"];    fmt.Println(request["params"])    // how do i get the keys and their values from params.    // note params is dynamic.    for _, v := range request["params"].(map[string]interface{}) {        // println(v)        switch t := v.(type) {        case string, []int:            fmt.Println(t)        default:            fmt.Println("wrong type")        }    }    sendRequest(requestType, requestUrl)}func sendRequest(type string, url string) string {    req, err := http.NewRequest(type, url, nil)    client := &http.Client{}    resp, err := client.Do(req)    if err != nil {        panic(err)    }    defer resp.Body.Close()    body, _ := ioutil.ReadAll(resp.Body)    fmt.Println("response Body:", string(body))    return string(body)}我如何遍歷參數是interface我如何獲得密鑰及其值
查看完整描述

1 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

您可以通過對 JSON 解組使用適當的結構來極大地簡化代碼:


type Request struct {

    URL    string                 `json:"url"`

    Params map[string]interface{} `json:"params"`

    Type   string                 `json:"type"`

}

然后你可以更簡單地解組它:


request := &Request{}

if err := json.Unmarshal([]byte(j), &request); err != nil {

    panic(err)

}

并訪問這樣的值:


requestType = request.Type

requestURL = request.URL

for key, value := range request.Params {

    switch v := value.(type) {

    case float64:

         // handle numbers

    case string:

         // handle strings

    }

}


查看完整回答
反對 回復 2023-03-29
  • 1 回答
  • 0 關注
  • 104 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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