dongwu5318 2017-07-12 10:36
浏览 140
已采纳

如何检测收到的JSON是否包含未知字段

I'm trying to find some way to prohibit arbitrary JSON keys and fields in Go. For now, if I send payload with undeclared fields in struct, the service will work normally and will map the entity described fields (likejson:"id,omitempty"). For example:

type Foo struct {
    Bar         int        `json:"id,omitempty"`
}

Received JSON:

{
  "id": 12,
  "hey": "hey"
}

Can anybody help me to find the way of tracking unknown field in payload? I need to return an error in that case.

  • 写回答

1条回答 默认 最新

  • dsogx84602 2017-07-12 11:48
    关注

    Update:

    you might want to use DisallowUnknownFields() read for more info


    old answer:

    There is a proposal for golang 1.9 on this: proposal: some way to reject unknown fields in encoding/json.Decoder

    Till then you could try something like this playground (code also below). The key idea is to parse the json into a map[string]interface{} and then work with the keys. This will of course get much more complicated if you have nested structs.

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Foo struct {
        Bar int `json:"id,omitempty"`
    }
    var allowedFooKeys = []string{"id"}
    
    func main() {
        b := []byte(`{
          "id": 12,
          "hey": "hey"
        }`)
        m := map[string]interface{}{}
    
        if err := json.Unmarshal(b, &m); err != nil {
            panic(err)
        }
    
        for k, _ := range m {
            if !keyExists(k, allowedFooKeys) {
                fmt.Println("Disallowed key in JSON:", k)
            }
        }
    }
    
    func keyExists(key string, keys []string) bool {
        for _, k := range keys {
            if k == key {
                return true
            }
        }
        return false
    }
    

    You can even get rid of the variable allowedFooKeys by getting the allowed keys directly from the Foo struct using reflect. For more info on that see here: How to read struct field ` ` decorators?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能