如何在 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 中解组可以是数组或字符串的字段? 的相关文章

  • 读取/写入本地 json 文件 swift 4

    请帮我 我在项目中添加了一个json文件 我的 json 文件 person title image Vitamin1 favorite false title B6 image Vitamin2 favorite false 我可以读取文
  • 改造如何打印响应 JSON

    我正在使用 Retrofit 并且想要访问从服务器返回的 JSON 响应 有人可以告诉我吗 谢谢 如果您只想查看出于调试目的的响应 只需在改造中打开调试并查看日志即可 它是这样的 restAdapter setDebuggingEnable
  • 通过 POST 将 JSON 编码的变量从 PHP 传递到 Javascript

    我有一个多维数组 我想将其发送到带有 Javascript 的 PHP 脚本 该脚本解析 JSON 数据并将其绘制在 Google 地图上 我正在尝试使用表单来模拟它
  • Cgo 生成的源无法在 MVC 上编译

    我有一个用 CGo 制作的共享库 它在 Linux 和 Android 上链接得很好 但是 当使用 Microsoft Visual Studio 2017 在 Windows 10 上进行编译时 出现以下错误 Microsoft R Pr
  • json_encode() 非 utf-8 字符串?

    所以我有一个字符串数组 并且所有字符串都使用系统默认值ANSI编码并从 SQL 数据库中提取 因此有 256 种不同的可能的字符字节值 单字节编码 有什么方法可以让我得到json encode 工作并显示这些字符而不必使用utf8 enco
  • 类方法的自定义代码完成?

    在 MATLAB 中 可以定义代码建议和完成 如标题为 的文档页面中所述 自定义代码建议和完成 https www mathworks com help matlab matlab prog customize code suggestio
  • WHERE BETWEEN 子句中的 PostgreSQL jsonb 值

    我的数据库表 a table 中有 jsonb 字段 其中包含 int 值 例如 abc def ghk 500 我将使用 WHERE 子句创建带有此字段 ghk 过滤器的 SELECT SELECT FROM a table WHERE
  • C# 中的 JSON 到 XML 转换

    我一直在使用 Json Net 将 JSON 解析为对象并转换为 XMLDocument 但我得到了 InvalidOperationException 该文档已经有一个 文档元素 节点 我有这个 JSON 数据 data name Ero
  • 将数组传递给 json.stringify

    我试图将数组传递给 json stringify 但返回的值返回为空 JSON stringify json data returns json 这是数据的内容 data from email protected cdn cgi l ema
  • Go 中数组的嵌套结构

    我已经开始使用https mholt github io json to go https mholt github io json to go 将 API JSON 转换为 go 结构 我真的很喜欢它 但是我对如何初始化如下所示的报告定义
  • 使用对象键作为 JSON 架构中的类型

    假设我想根据 Intellij IDEA 中的 JSON 架构验证 YAML 文件 该文件的结构如下 foo command touch tmp a txt I know I don t need this but it s an exam
  • 读取原始输入行并输出单个数组

    我有一个目录 其中包含文件 我想从该文件列表创建一个数组 我以为这会很容易 比如 ls mydir jq R file1 file2 file3 我唯一能弄清楚的是 ls mydir jq sR split n select length
  • golang从sdin扫描一行数字

    我正在尝试从标准输入读取输入 3 2 1
  • 如何使用 Codable 解析此 JSON?

    我一直在尝试从我的中解析这个对象JSON并不断收到此错误 错误 类型不匹配 Swift Array Swift DecodingError Context codingPath debugDescription 本应解码数组 但找到了字典
  • 如何告诉杰克逊在反序列化期间忽略空对象?

    在反序列化过程中 据我理解是将JSON数据转换为Java对象的过程 我如何告诉Jackson 当它读取不包含数据的对象时 应该忽略它 我正在使用 Jackson 2 6 6 和 Spring 4 2 6 我的控制器收到的JSON数据如下 i
  • 有没有办法将 JSON 模式转换为 XSD? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我目前正在寻找一种将 JSON 架构转换为 XSD 或 XML 架构的方法 我没有找到任何关于这个主题
  • 将单引号括起来的数组转换为数组

    深度嵌套在 JSON 对象中我有属性value actions name InviteUser type button value Brian Timoney email protected cdn cgi l email protecti
  • Jackson Json 将对象反序列化为列表

    我正在使用 Spring 的 Web 服务RestTemplate并反序列化Jackson 在来自服务器的 JSON 响应中 其中一个字段可以是对象或列表 这意味着它可以是 result or result 有没有办法通过对我要反序列化的类
  • 嵌套对象的 AJV 模式验证

    函数返回的对象看起来像这样 answer vehicle type 1 message Car model VW color red 答案 对象始终存在 其他字段基于 vehicle type E g 如果vehicle type 1 则有
  • 无需时间即可生成随机字符串?

    我知道如何使用 Runes 和播种 rand Init 在 go 中生成随机字符串time UnixNano 我的问题是 是否可以 使用 stdlib 在不使用当前时间戳 安全 的情况下播种 rand 此外 我问 因为仅仅依靠时间来为敏感操

随机推荐