stringgosplitglide-golang

How do I extract a part of a string


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.


Solution

  • 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