Bash 根据公共 ID 匹配 2 json 个文件

Bash match 2 json files based on common id

我希望根据公共 ID 匹配 2 个 json 文件 我尝试过以多种不同的方式使用 awk、jq 和 npm json 包,但没有任何方法可以正常工作。 2 json 个文件未排序且不包含所有相同的条目。它们包含通用的 networkId,我只希望输出包含 file2 中的条目。 希望有人能帮忙! 这是一个例子。

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"
  }
]

想要的输出:

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

这是 INDEXJOINadd 的任务:

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