【发布时间】:2020-10-14 17:26:01
【问题描述】:
我正在尝试将带有一些基于正则表达式的规则的 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
}
【问题讨论】:
-
你不能,不能直接。您需要一个将正则表达式类型作为字段的自定义类型,然后让自定义类型实现 json unmarshaler 接口。如果您希望能够直接通过自定义类型使用正则表达式方法,则可以嵌入该字段。
-
或者你可以在
GithubProjectMatcherRule上写一个自定义的UnmarshalJSON。无论哪种方式,您都希望将 JSON 中的 RE 存储为纯字符串,并在解组期间将Compile存储到regexp.Regexp。 -
谢谢,我早该知道的,以前做过。将在此处分享结果作为答案以及未来的读者。
-
包 encoding/json 文档的哪一部分暗示了这是可能的? *regexp.Regexp 在这个包可以处理的类型中吗?