Home >Backend Development >Golang >How to extract key-value pairs in JSON using regular expressions in Go language
How to use regular expressions to extract key-value pairs in JSON in Go language
Introduction:
There are many ways to extract key-value pairs in JSON in Go language, one of which is A common method is to use regular expressions. Regular expressions are powerful text matching patterns that can quickly search and extract the required information in text. This article will introduce how to use regular expressions to extract key-value pairs in JSON in Go language, and illustrate it with code examples.
Text:
In Go language, you can use the regexp
package to implement the function of regular expressions. Suppose we have the following JSON data:
{ "name": "Alice", "age": 25, "gender": "female" }
Our goal is to extract the key-value pairs in JSON, namely name: Alice
, age: 25
and gender: female
.
First, we need to create a regular expression to match key-value pairs in JSON. In this example, we can use the following regular expression:
`"(w+)":s*"([^"]+)"`
Explain this regular expression:
"(w )":
: Matches key names enclosed in double quotes and uses parentheses to capture the key name. :s*
: Matches possible whitespace characters after the colon. "([^"] )"
: Matches a string value enclosed in double quotes and uses parentheses to capture the string value. Continue Next, we will use this regular expression in Go code to extract key-value pairs in JSON. The following is a complete sample code:
package main import ( "fmt" "regexp" ) func main() { jsonData := `{ "name": "Alice", "age": 25, "gender": "female" }` re := regexp.MustCompile(`"(w+)":s*"([^"]+)"`) match := re.FindAllStringSubmatch(jsonData, -1) for _, pair := range match { key := pair[1] value := pair[2] fmt.Printf("%s: %s ", key, value) } }
Run the above code, the output result is:
name: Alice age: 25 gender: female
Code explanation:
jsonData
, which contains the JSON data to be extracted. function creates a regular expression object
re to match key-value pairs in JSON.
Function, pass in the string to be matched and -1 (meaning to match all results), and return a two-dimensional array
match, each row is the matching result of a key-value pair.
to loop through the
match array, extract the key name and key value, and print them out.
This article introduces how to use regular expressions in Go language to extract key-value pairs in JSON. By using the
regexp package, we can create a regular expression object and then use the object to match the key-value pairs in JSON Key-value pairs. In this way, we can easily extract the required information from the JSON data.
Unmarshal function provided by the
encoding/json package.
The above is the detailed content of How to extract key-value pairs in JSON using regular expressions in Go language. For more information, please follow other related articles on the PHP Chinese website!