如何在 Go 中解组可以是数组或字符串的字段?

2024-04-26

我正在尝试解组该文件:

{
  "@babel/[email protected] /cdn-cgi/l/email-protection": {
    "licenses": "MIT",
    "repository": "https://github.com/babel/babel/tree/master/packages/babel-code-frame",
    "publisher": "Sebastian McKenzie",
    "email": "[email protected] /cdn-cgi/l/email-protection",
    "path": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/@babel/code-frame",
    "licenseFile": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/@babel/code-frame/LICENSE"
  },
  "[email protected] /cdn-cgi/l/email-protection": {
    "licenses": [
      "AFLv2.1",
      "BSD"
    ],
    "repository": "https://github.com/kriszyp/json-schema",
    "publisher": "Kris Zyp",
    "path": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/json-schema",
    "licenseFile": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/json-schema/README.md"
  }
}

进入这个结构:

type Dependency struct {
    Name    string
    URL     string
    Version string
    License string
}

使用这些说明:

dependencies := map[string]*json.RawMessage{}
err = json.Unmarshal(file, &dependencies)
// boilerplate

for key, value := range dependencies {
    depVal := map[string]string{}
    err = json.Unmarshal(*value, &depVal)
    // boilerplate
    result = append(result, depVal)
}

问题在于“[电子邮件受保护] /cdn-cgi/l/email-protection“我们有一个许可证数组而不是一个字符串,因此我显然得到了

json: cannot unmarshal array into Go value of type string 

有没有办法自动处理字段license哪个可以是数组或字符串?

Thanks


不幸的是,没有提供真正的自动解决方案json包裹。

但是您可以将依赖项解组到map[string]*json.RawMessage代替map[string]string. json.RawMessage只是一个[]byte,因此您可以根据第一个字节决定消息的类型。

Example:

for _, value := range dependencies {
    depVal := map[string]*json.RawMessage{}

    _ = json.Unmarshal(*value, &depVal)

    // check if the first character of the RawMessage is a bracket
    if rune([]byte(*depVal["licenses"])[0]) == '[' {
        var licenses []string
        json.Unmarshal(*depVal["licenses"], &licenses)
        fmt.Println(licenses)
        // do something with the array
    }

    result = append(result, Dependency{
        URL:     string(*depVal["repository"]),
        License: string(*depVal["licenses"]),
    })
}

另一种解决方案是使用 2 个结构。一个包含字符串形式的依赖项,另一个包含数组形式的依赖项。然后您可以尝试致电json.Unmarshal在他们俩身上。 例子:


type Dependency struct {
    Licenses string
    // other fields
}

type DependencyWithArr struct {
    Licenses []string
    // other fields
}

// in your function
for _, value := range dependencies {
    type1 := Dependency{}
    type2 := DependencyWithArr{}

    err = json.Unmarshal(*value, &type1)
    if err != nil {
        err = json.Unmarshal(*value, &type2)
        // use the array type
    } else {
        // use the single string type
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Go 中解组可以是数组或字符串的字段? 的相关文章

随机推荐