How do I extract a part of a string

90 Views Asked by At

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.

1

There are 1 best solutions below

2
On BEST ANSWER

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