go用regex提取json文件的内容常用示例
以下是使用正则表达式从JSON文件中提取内容的常见示例:
- 提取所有键值对:
"([^"]+)":\s*"([^"]+)"
示例代码:
package main
import (
"fmt"
"io/ioutil"
"regexp"
)
func main() {
data, err := ioutil.ReadFile("data.json")
if err != nil {
fmt.Println("Error reading file:", err)
return
}
re := regexp.MustCompile(`"([^"]+)":\s*"([^"]+)"`)
matches := re.FindAllStringSubmatch(string(data), -1)
for _, match := range matches {
key := match[1]
value := match[2]
fmt.Printf("Key: %s, Value: %s\n", key, value)
}
}
- 提取特定键的值:
"keyName":\s*"([^"]+)"
示例代码:
package main
import (
"fmt"
"io/ioutil"
"regexp"
)
func main() {
data, err := ioutil.ReadFile("data.json")
if err != nil {
fmt.Println("Error reading file:", err)
return
}
re := regexp.MustCompile(`"keyName":\s*"([^"]+)"`)
match := re.FindStringSubmatch(string(data))
if len(match) > 1 {
value := match[1]
fmt.Println("Value:", value)
} else {
fmt.Println("Key not found")
}
}
请注意,使用正则表达式提取JSON数据是一种简单的方法,但并不适用于所有情况。对于复杂的JSON结构,建议使用专门的JSON解析器
原文地址: https://www.cveoy.top/t/topic/inlL 著作权归作者所有。请勿转载和采集!