【问题标题】:Jq: appending an object from 1 file into another fileJq:将一个文件中的对象附加到另一个文件中
【发布时间】:2018-02-12 13:37:39
【问题描述】:

使用 jq,我如何从文件 (input_02.json) 中获取 json 对象,并将其附加到 output.json,同时保留 output.json 中的所有内容(例如,源自文件 input_01.json 的对象)。

在这两种情况下要附加的对象实际上是文件的全部内容,文件的“id”字段作为对象的键。

我正在获取大量输入文件(所有文件都具有相同的语法),并基本上像这样组合它们。

我用来创建要追加的对象的命令如下:

jq '{(.id):(.)} ' input_01.json

这给了我:

{
  "input1_id": {

  }
}

input_1.json:

{
  "id": "input1_id",
  "val: "testVal1
}

input2.json:

{
  "id": "input2_id",
  "val: "testVal2
}

想要的输出:

{
  "input1_id": {
    "id": "input1_id",
    "val: "testVal1
  },
  "input2_id": {
    "id": "input2_id",
    "val: "testVal2
  }
}

【问题讨论】:

  • 发布input_02.json 内容和预期结果
  • @RomanPerekhrest 完成。

标签: json object merge jq


【解决方案1】:

{(.id):(.)} 让您走在正确的轨道上。以下应该处理您提到的案例,并且可能会给您一些关于类似案例的想法:

program.jqmap({(.id):(.)}) | add

调用:

jq -s -f program.jq input_01.json input_02.json

【讨论】:

    【解决方案2】:

    您可以在https://pypi.python.org/pypi/jf 中使用“jf”

    $ pip install jf
    
    $ jf 'chain(), {y["id"]: y for y in x}' input1.json input2.json
    {
      "input2_id": {
        "id": "input2_id",
        "val": "testVal2"
      },
      "input1_id": {
        "id": "input1_id",
        "val": "testVal1"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2021-03-09
      • 2020-03-19
      • 1970-01-01
      相关资源
      最近更新 更多