我正在尝试使用基于正则表达式的一些规则来解码JSON文件。
请参阅下面的结构。
// GithubProjectMatcher matches a repository with a project
type GithubProjectMatcher struct {
Rules map[string]GithubProjectMatcherRule `json:"rules,omitempty"`
}
// GithubProjectMatcherRule rule that matches a repository to a project
type GithubProjectMatcherRule struct {
URL *regexp.Regexp `json:"url,omitempty"`
}
看到这里我的JSON{
"rules": {
"Project One": { "url": "tabia|varys|garo" },
"Project Two": { "url": "(?i)lem\\-" },
}
}
如果我用代码对这些正则表达式进行硬编码,则它们将起作用。例如
regexp.MustCompile("tabia|varys|garo")
为了将它们解码到我的结构中,必须做些什么?我尝试解码如下。
f, err := os.Open("rules.json")
if err != nil {
return err
}
defer f.Close()
err := json.NewDecoder(f).Decode(&m)
if err != nil {
return err
}
最佳答案
(联合国)编码(marshal)正则表达式很容易。它只需要创建一个嵌入regexp.Regexp
的自定义类型:
import "regexp"
// MyRegexp embeds a regexp.Regexp, and adds Text/JSON
// (un)marshaling.
type MyRegexp struct {
regexp.Regexp
}
// Compile wraps the result of the standard library's
// regexp.Compile, for easy (un)marshaling.
func Compile(expr string) (*MyRegexp, error) {
re, err := regexp.Compile(expr)
if err != nil {
return nil, err
}
return &MyRegexp{*re}, nil
}
// UnmarshalText satisfies the encoding.TextMarshaler interface,
// also used by json.Unmarshal.
func (r *MyRegexp) UnmarshalText(text []byte) error {
rr, err := Compile(string(text))
if err != nil {
return err
}
*r = *rr
return nil
}
// MarshalText satisfies the encoding.TextMarshaler interface,
// also used by json.Marshal.
func (r *MyRegexp) MarshalText() ([]byte, error) {
return []byte(r.String()), nil
}
关于json - 将json字段解码为* regexp.Regexp类型的struct字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62555285/