用JWT编码的Golang解析图

x0fgdtte  于 2023-11-14  发布在  Go
关注(0)|答案(1)|浏览(105)

在我的golang项目中,我需要解析和解码一些数据,编码在JWT token中。为此,我使用github.com/lestrrat-go/jwx/jwt。数据如下:

"ver": "some ver", 
"pds": {
  "r": [
    {
      "comp": "some_string",
      "dur": 20,
      "u": "DAY",
      "res": "some other string"
    }
  ]
}

字符串
所以我可以解码基本字符串(ver),这很简单,但我不能解码对象和数组,并不断得到一个错误。我尝试了以下方法:

tokenRaw := "my_jwt_token_here"
reader := strings.NewReader(tokenRaw)
token, err := jwt.Parse(reader)
if err != nil {
    return nil, err
}

type pdsrStruct struct {
    Comp     string `json:"comp"`
    Duration int    `json:"dur"`
    Unit     string `json:"u"`
    Res      string `json:"res"`
}
type R []pdsrStruct
type Pds map[string]R

var ok bool
var pds Pds
if ret, found := token.Get("pds"); found {
    if pds, ok = ret.(Pds); !ok {
        return nil, er.Errorf("failed to parse")
    }
}


有什么好的建议都欢迎。谢谢。

7bsow1i6

7bsow1i61#

package main

import (
   "encoding/json"
   "fmt"
)

var text = []byte(`
{
   "pds": {
      "r": [
         {
            "dur": 20,
            "u": "DAY"
         }
      ]
   }
}
`)

func main() {
   var s struct {
      Pds struct {
         R []struct {
            Dur int
            U string
         }
      }
   }
   json.Unmarshal(text, &s)
   fmt.Printf("%+v\n", s) // {Pds:{R:[{Dur:20 U:DAY}]}}
}

字符串

相关问题