Home > Back-end >  Bash match 2 json files based on common id
Bash match 2 json files based on common id

Time:04-28

I wish to match 2 json files based on common id I've tried using awk, jq and the npm json package in quite a lot of different ways but nothing have gotten close to working. The 2 json files are not sorted and do not contain all the same entries. they contain the common networkId, I only want the output to contain the entries from file2. Hope somebody can help! Here's an example.

file1.json:

[
  {
    "customerId": "id1",
    "networkId": "L_653021545945744804"
  },
  {
    "customerId": "id2",
    "networkId": "L_653021545955724805"
  },
  {
    "customerId": "id3",
    "networkId": "L_655051945958724557"
  },
  {
    "customerId": "id4",
    "networkId": "L_655567989968735408"
  }
]

file2.json:

[
  {
    "name": "a",
    "networkId": "L_653021545945744804"
  },
  {
    "name": "b",
    "networkId": "L_655051945958724557"
  }
]

Wanted output:

[
  {
    "customerId": "id1",
    "name": "a",
    "networkId": "L_653021545945744804"
  },
  {
    "customerId": "id3",
    "name": "b",
    "networkId": "L_655051945958724557"
  }
]

CodePudding user response:

This is a task for INDEX, JOIN and add:

jq '[JOIN(INDEX(.networkId); input[]; .networkId; add)]' file1.json file2.json
[
  {
    "name": "a",
    "networkId": "L_653021545945744804",
    "customerId": "id1"
  },
  {
    "name": "b",
    "networkId": "L_655051945958724557",
    "customerId": "id3"
  }
]

Demo

  • Related