douyan1927 2018-02-19 00:31 采纳率: 0%
浏览 48

如何在JSON键中使用GO中的switch?

Here is an example of POST request body:

{"action":"do_something","id":"001"}

I took an example of simple json parser

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type some_json struct {
    Action string `json:"action"`
    Id string `json:"id"`

}

func jsonparse(rw http.ResponseWriter, request *http.Request) {
    decoder := json.NewDecoder(request.Body)

    var post_data some_json
    err := decoder.Decode(&post_data)

    if err != nil {
        panic(err)
    }


    switch ***WHAT_SHOULD_BE_HERE???*** {
    default :
      fmt.Fprintf(w,"WRONG PARAM")
    case "some_thing":
      fmt.Fprintf(w,post_data.Id + "

")
            }
}

func main() {
    http.HandleFunc("/", jsonparse)
    http.ListenAndServe(":8080", nil)
}

I already know how to switch cases from form values, but how to switch cases of json key values?

  • 写回答

1条回答 默认 最新

  • dpn68721 2018-02-19 05:54
    关注

    I am not sure what you want to switch, but i think that you just need to erase the () so Action is not a function call anymore

    Be careful maybe your error is that u mixed up the strings in JSON: "do_something" in case: "some_thing"

    You can copy following code to playground

    package main
    
    import (
        "encoding/json"
        "fmt"
        "strings"
    )
    
    type some_json struct {
        Action string `json:"action"`
        Id     string `json:"id"`
    }
    
    func jsonparse() {
        r := strings.NewReader("{\"action\":\"do_something\",\"id\":\"001\"}")
        decoder := json.NewDecoder(r)
    
        var post_data some_json
        err := decoder.Decode(&post_data)
    
        if err != nil {
            panic(err)
        }
    
        switch post_data.Action {
        default:
            fmt.Println( "WRONG PARAM")
        case "do_something":
            fmt.Println( post_data.Id+"
    
    ")
        }
    }
    
    func main() {
        jsonparse()
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题