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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?