How to extract part of a string

王林
Release: 2024-02-08 22:39:22
forward
1132 people have browsed it

How to extract part of a string

php editor Apple brings you an article on how to extract part of a string. In programming, we often need to extract the required part from a string, such as getting the file extension, intercepting a piece of text, etc. This article will introduce several commonly used methods and functions to help you easily implement the string extraction function. Whether you are a beginner or a developer with some programming experience, this article can provide you with practical tips and methods to get twice the result with half the effort when processing strings. Come and learn!

Question content

I need to get part of the string, namely: { "Token":"eyJ0eXjskdckjasdcaksdclkasdcsjnsc", "Timestamp expired": 9234234 }

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

Workaround

You should parse it as 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)
Copy after login

Or create a dedicated struct for unmarshalling:

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
Copy after login

The above is the detailed content of How to extract part of a string. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!