0

I'm need to get a part a of a string, i.e.: { "token":"eyJ0eXjskdckjasdcaksdclkasdcsjnsc", "expiresOnTimestamp":9234234 }

I've tried using split, splitafter. I need to get this token, just the token.

  • 4
    Your input is a JSON string, so treat it like that: use `encoding/json`. Do not try to split it. Or even better: since it's a JWT token, use a library that is specialized on that. – icza Jan 07 '23 at 21:19
  • My bad, It's not an input it's an output, thats the response that I get for consuming a POST resquest, and I need to use only the token part. – DanielAlzate Jan 09 '23 at 15:38

1 Answers1

5

You should parse it to map[string]interface{}:

jsonInput := []byte(`{ "token":"eyJ0eXjskdckjasdcaksdclkasdcsjnsc", "expiresOnTimestamp":9234234 }`)
jsonContent := make(map[string]interface{})

unmarshalErr := json.Unmarshal(jsonInput, &jsonContent)

if unmarshalErr != nil {
    panic(unmarshalErr)
}

token, _ := jsonContent["token"].(string)

Or create a dedicated struct for unmarshal:

type Token struct {
    Value              string `json:"token"`
    ExpiresOnTimestamp int    `json:"expiresOnTimestamp"`
}

jsonInput := []byte(`{ "token":"eyJ0eXjskdckjasdcaksdclkasdcsjnsc", "expiresOnTimestamp":9234234 }`)

var jsonContent Token

unmarshalErr := json.Unmarshal(jsonInput, &jsonContent)

if unmarshalErr != nil {
    panic(unmarshalErr)
}

token := jsonContent.Value
Oshawott
  • 539
  • 5
  • 12