在特定键1.4下使用jq合并两个文件中的对象数组 [英] combine array of objects from two files with jq under specific key 1.4

查看:74
本文介绍了在特定键1.4下使用jq合并两个文件中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件,这些文件具有以下JSON,需要使用每个对象的相对数组位置进行合并:

I have two files with the following JSON that I need to combine using the relative array position of each object:

PS:-我在Solaris上只能使用1.4版,因此没有[inputs]功能

PS: - I am restricted to version 1.4 as am on Solaris so don't have the [inputs] feature

文件1

{
  "input": [
    {
      "email": "test1@gm.com",
      "firstName": "Fred"
    },
    {
      "email": "someone@gm.com",
      "firstName": "James"
    }
  ]
}

文件2:

{
  "result": [
    {
      "id": 50,
      "status": "created"
    },
    {
      "id": 51,
      "status": "rejected"
    }
  ]
}

预期结果是input [1]的元素与result [1]的元素组合,依此类推,如下所示:

the expected result is the elements of input[1] combined with elements of result[1] and so on as follows:

{
  "combined": [
    {
      "email": "test1@gm.com",
      "firstName": "Fred",
      "id": 50,
      "status": "created"
    },
    {
      "email": "someone@gm.com",
      "firstName": "James",
      "id": 51,
      "status": "rejected"
    }
  ]
}

推荐答案

您可以使用--slurp选项将两个文件读取到一个数组中,从那里循环遍历其中一个数组的键相对容易,并且将两个数组的对应元素加在一起.

You can use the --slurp option to read both files into one array, and from there it's relatively simple to loop over the keys of one of the arrays and add the corresponding elements of both arrays together.

jq --slurp '
{
  combined: [
    .[0].input as $is|
    .[1].result as $rs|
    range(0; $is|length) as $n|
    $is[$n]+$rs[$n]
  ]
}
' file1.json file2.json

这篇关于在特定键1.4下使用jq合并两个文件中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆