我有一个带有json数组的json文件list_values.json,该数组带有一个"Origine"字段:

[
        {
          "origine": "reason1",
          "identifiant": "1234_AAA"
        },
        {
          "origine": "reason3",
          "identifiant": "5678_BBB"
        }
]

我有mapping.json个文件,其中包含一系列预定义的字段:

{
  "REASON_0": "reason0",
  "REASON_1": "reason1",
  "REASON_2": "reason2",
  "REASON_3": "reason3",
  "REASON_4": "reason4"
}

我使用JQ编写了一个bash脚本,代码如下:

jq '.[] |= . + {"type": (.identifiant | split("_") | .[1] )}' list_values.json > add_fields.json

我的档案add_fields.json:

[
        {
          "origine": "reason1",
          "identifiant": "1234_AAA",
          "type": "AAA"
        },
        {
          "origine": "reason3",
          "identifiant": "5678_BBB",
          "type": "BBB"
        }
]

我想添加一个等于关键字mapping.json的"Reason"字段,其值与"Origine"字段list_values.json匹配.如下所示:

[
        {
          "origine": "reason1",
          "identifiant": "1234_AAA",
          "type": "AAA",
          "reason": "REASON_1"
        },
        {
          "origine": "reason3",
          "identifiant": "5678_BBB",
          "type": "BBB",
          "reason": "REASON_3"
        }
]

我能用JQ做什么呢?

我指定值mapping.json作为键是唯一的.

推荐答案

下面的代码看起来是可理解和可扩展的:它首先构建一个Lookup对象(具有INDEX个),然后将每个输入对象映射到一个具有添加的属性的新对象:

jq 'INDEX(input|to_entries[]; .value) as $mapping
| map(
  .type=(.identifiant/"_"|last)
  | .reason=$mapping[.origine].key
)' list_values.json mapping.json

或者,将具有新属性的对象合并到数组的现有项中:

jq 'INDEX(input|to_entries[]; .value) as $mapping
| .[]
|= . + {
  type: (.identifiant / "_" | last),
  reason: $mapping[.origine].key
}' list_values.json mapping.json

输出:

[
  {
    "origine": "reason1",
    "identifiant": "1234_AAA",
    "type": "AAA",
    "reason": "REASON_1"
  },
  {
    "origine": "reason3",
    "identifiant": "5678_BBB",
    "type": "BBB",
    "reason": "REASON_3"
  }
]

Json相关问答推荐

如何在JMESPath中区分空和假?

如何获取brew list作为JSON输出

对面的行/列进行排序时可能出现错误

Golang返回的JSON顶级字段是可变的.如何在 struct 中使用

如何创建生成两个不同对象的JSON数组的SQL查询?

使用PowerShell解析文件并获取特定行的值

织女星-没有循环的动画条形图第二部分(实际上是织女星)

集成wix.comstore API|变音符号问题

如何对未知/变量键的字典进行编码?

Jolt 不打印任何东西

使用 jq 和 awk 拆分大型 JSON 文件

为什么JsonConvert反序列化对象以int但不长失败

字典和对象的模型创建问题

如何为所有 API 端点全局设置 http.ResponseWriter Content-Type 标头?

JSON 模式验证

Jackson Json:如何将数组转换为 JsonNode 和 ObjectNode?

jquery用json数据填充下拉列表

使用 ajax 将 JSON 发送到 PHP

带有 Jackson 的不可变 Lombok 注释类

在没有 ASP.NET Core 的情况下将 IConfigurationSection 绑定到复杂对象