duanshan1977 2018-09-06 07:43
浏览 43
已采纳

如何发送动态JSON键/值作为请求参数

package main

import (
    "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)
}
  1. How do I iterate through params that is an interface
  2. how do i get the key and its values
  • 写回答

1条回答 默认 最新

  • doushi3454 2018-09-06 08:18
    关注

    You can greatly simplify your code by using a proper struct for your JSON unmarshaling:

    type Request struct {
        URL    string                 `json:"url"`
        Params map[string]interface{} `json:"params"`
        Type   string                 `json:"type"`
    }
    

    Then you can unmarshal it more simply as so:

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

    And access the values as such:

    requestType = request.Type
    requestURL = request.URL
    for key, value := range request.Params {
        switch v := value.(type) {
        case float64:
             // handle numbers
        case string:
             // handle strings
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看