Map array to other array values in JQ

Viewed 396

How to map array to other array values in jq?

I have two JSON arrays.

[
  {
    "date": "2021/9/12",
    "rate": 7,
    "path": "f"
  },
  {
    "date": "2021/9/13",
    "rate": 8,
    "path": "f"
  },
  {
    "date": "2021/9/14",
    "rate": 8,
    "path": "f"
  },
]
[
  "562949953740755",
  "562949953740743",
  "562949953740744"
]

I want to have a result like this below.

[
  {
    "date": "2021/9/12",
    "rate": 7,
    "path": "f",
    "inode": "562949953740755"
  },
  {
    "date": "2021/9/13",
    "rate": 8,
    "path": "f",
    "inode": "562949953740743"
  },
  {
    "date": "2021/9/14",
    "rate": 8,
    "path": "f",
    "inode": "562949953740744"
  },
]

I tried: But I have no clue how to achieve this.

jq -s '.[1] as $file | .[0] | (.[].path) |= (range($file|length) as $i | $file[$i]) ' <(cat a.json) <(cat b.json)
2 Answers

Don't reinvent the transpose wheel.

jq -s 'transpose | map(.[0] + {inode: .[1]})' a.json b.json

Online demo

Use the array file (inode) as reference and slurp its content ahead of processing the original file.

jq --slurpfile inode b.json '
  reduce range(0, ($inode[0]|length)) as $d (.; .[$d] += {inode: $inode[0][$d]})' a.json

Note that, this works as long as there are equal number of elements in both your JSON arrays.

Another attempt without involving any "slurps" of the input file (probably faster than the earlier one)

jq -n 'input as $inode | input | 
  reduce range(0, length) as $d (.; .[$d] += {inode: $inode[$d]})' b.json a.json
Related