json - 将json字段解码为* regexp.Regexp类型的struct字段

标签 json regex go

我正在尝试使用基于正则表达式的一些规则来解码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/

相关文章:

java 用正则表达式分割字符串

ruby - 在 Ruby 中使用命名正则表达式组

go - Gzip 未压缩的 http.Response.Body

go - 如何在golang中获取带引号的可打印字符串

go - GRPC 消息结构

json - postgresql中group by的嵌套json聚合行

java - 使用 JAVA 从 JSON 文件(嵌套对象数组)打印特定值

javascript - javascript 无法识别 Django 变量

php - Opencart:Ajax json响应未知字符

Ruby RegEx 用于搜索和替换