Home > Back-end >  jq add fields from a file into another file
jq add fields from a file into another file

Time:01-10

I have 2 files (which are quite long):

file1.json (540 objects - i'll write just 2 mockups for ease of use)

[
  {
    "a": "apple",
    "b": "banana",
    "c": ["car1", "car2", "car3"],
    "d": ["doodle1", "doodle2", "doodle3"],
    "e": "elephant"
  },
  {
    "a": "aqua",
    "b": "bay",
    "c": ["carrot", "chile", "cucumber"],
    "d": ["dice", "drop", "dang"],
    "e": "elastic"
  }
]

file2.json (540 objects - i'll write just 2 mockups for ease of use)

[
  {
    "l": ["link1", "link2", "link3"]
  },
  {
    "l": ["link4", "link5", "link6"]
  }
]

expected result

[
  {
    "a": "apple",
    "b": "banana",
    "c": ["car1", "car2", "car3"],
    "d": ["doodle1", "doodle2", "doodle3"],
    "e": "elephant",
    "l": ["link1", "link2", "link3"]
  },
  {
    "a": "aqua",
    "b": "bay",
    "c": ["carrot", "chile", "cucumber"],
    "d": ["dice", "drop", "dang"],
    "e": "elastic",
    "l": ["link4", "link5", "link6"]
  }
]

Is this possible to achieve this with jq or should I process it through other programming languages like python or javascript?

CodePudding user response:

jq is a perfect choice for all kinds of JSON processing. In this case, you could transpose an array of the contents of both files, then add up the aligned items using a map:

jq -n '[inputs] | transpose | map(add)' file1.json file2.json

Demo

  • Related