【问题标题】:Using jq to load one json file into the hash of another json file使用 jq 将一个 json 文件加载到另一个 json 文件的哈希中
【发布时间】:2017-12-14 21:49:05
【问题描述】:

我试图弄清楚如何使用jq 将一个 json 文件的内容加载到另一个文件的哈希中。例如:

这个文件:

{
  "annotations": {...},
  "rows": [ {...}, {...}]
}

应在哈希仪表板中插入此文件:

{
  "dashboard": { },
  "overwrite": true,
  "message": "new commit"
}

所以生成的文件应该是

{
  "dashboard": {
     "annotations": {...},
     "rows": [ {...}, {...}]
  },
  "overwrite": true,
  "message": "new commit"
}

我想用管道来做 |或 |= 运算符,但我不知道如何使用一个内容并将其分配给另一个文件的选择过滤器。

【问题讨论】:

    标签: json merge jq


    【解决方案1】:

    jq解决办法:

    jq --slurpfile annot annot.json '.dashboard |= $annot[0]' dashb.json
    

    --slurpfile variable-name filename:

    此选项读取命名文件中的所有 JSON 文本并绑定一个 解析 JSON 值的数组到给定的全局变量。

    【讨论】:

    • --slurpfile 选项是我所需要的,必须更新 jq 然后就很明显了!谢谢!
    【解决方案2】:

    如果您的 jq 没有 --slurpfile,那么您可以例如运行 jq,如下所示:

    jq -s '.[0] as $fragment | .[1] | (.dashboard |= $fragment)' fragment.json dashboard.json
    

    【讨论】:

    • 那样做也不错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2018-01-25
    • 2019-12-09
    • 2017-12-03
    相关资源
    最近更新 更多