bash + jq:尝试读取两个 json 文件并构造一个新文件

问题描述 投票:0回答:1

我有以下 json 文件:

common.json

{
    "common": {
        "Hello": "ABC"
    },
    "east": {
        "Direction": "East"
    },
    "west": {
        "Direction": "West"
    }
}

pi.json

{
    "common": {
       "MyUri": "www.myuri.com"
    },
    "east": {
        "App-Env": "my-pi",
        "SentinelValue": 1713311902
    },
    "west": {
        "App-Env": "my-piw",
        "SentinelValue": 1713311902
    }
}

基本上我想创建一个新的json文件,其中包含common.json的“east”键+common.json的“common”键+pi.json的“common”键+pi.json的“east”键的所有内容被移至一个 json 文件。

我的以下脚本没有按照我想象的方式工作:

  jq_input_files=("common.json" "pi.json")

  jq --slurp 'map({
                 ((.common | keys_unsorted[])): .common[],
                 ((.east | keys_unsorted[])): .east[]
             }) | add' "${jq_input_files[@]}" > "test.json"

该脚本中 test.json 的内容是:

{
  "MyUri": "www.myuri.com",
  "App-Env": my-pi,
  "SentinelValue": 1713311902
}

我想要的 test.json 输出是:

{
  "MyUri": "www.myuri.com",
  "App-Env": 1713311902,
  "SentinelValue": 1713311902,
  "Hello": "ABC",
  "Direction": "East"
}

我无法弄清楚的两个主要问题:

  1. 即使传入了两个文件,似乎也没有从我的 common.json 文件中提取任何内容。
  2. 看来 App-Env 现在正在更新为与我的 SentinelValue 相同的值,这是我不希望发生的情况。
bash jq
1个回答
0
投票

--slurp
将两个文件放入一个数组中,但仍然不单独寻址它们。

来自 common.json 的“east”键 + common.json 的“common”键 + pi.json 的“common”键 + pi.json 的“east”键

您可以通过

first
last
(或
.[0]
.[1]
)来称呼他们:

first.east + first.common + last.common + last.east

演示

如果添加顺序并不重要(如果发生冲突,后者会覆盖前者),您可以坚持使用

map
并将所有内容放在一起。最后,使用
add
将它们汇总为一个对象:

map(.east, .common) | add

演示

© www.soinside.com 2019 - 2024. All rights reserved.