将单个的键值对映射使用 jq 合并成一个单一的映射。

huangapple go评论60阅读模式
英文:

join individual key:value maps into a single map using jq

问题

{
"Key1": "value1",
"Key2": "value2",
"Key3": "value3",
"Key4": "value4"
},
{
"Key1": "value1",
"Key2": "value2",
"Key3": "value3",
"Key4": "value4"
}

英文:

Hi I have below code which has individual key:value maps needs to be merged into a single key:value map

From below code

{
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
}
{
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
}

To below code using jq

{
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
},
{
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
}

答案1

得分: 0

I cannot find the dupe, so here goes.

要将每个文件添加为一个大数组的元素,您可以使用 -s/--slurpidentity filter .:

jq -s '.'

… 或者将 inputs 收集到 一个数组中 (使用 -n/--null-input):

jq -n '[inputs]'

或者不使用 -n:

jq '[., inputs]'

您可以在 https://stackoverflow.com/questions/73843868/difference-between-slurp-null-input-and-inputs-filter 上了解 slurping 与 consuming inputs 之间的区别。

Output:

[
  {
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
  },
  {
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
  }
]
英文:

I cannot find the dupe, so here goes.

To add each file as element into one big array, you can use -s/--slurp with the identity filter .:

jq -s '.' file1.json file2.json

… or collect inputs into an array (with -n/--null-input):

jq -n '[inputs]' file1.json file2.json

or without -n:

jq '[., inputs]' file1.json file2.json

You can read more about the differences of slurping vs consuming inputs in https://stackoverflow.com/questions/73843868/difference-between-slurp-null-input-and-inputs-filter

Output:

[
  {
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
  },
  {
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
  }
]

huangapple
  • 本文由 发表于 2023年7月5日 00:06:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76614334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定