使用 jq 根据键值合并两个 json 值

using jq to merge two json values based on key value

我有两个 json 文件,我想根据键值合并它们。两个 json 文件中的键名不同,但值相同。我正在使用 jq 来尝试完成这项工作。我发现的大多数示例都是基于键名而不是值进行合并的。

sample1.json

 [
  {
    "unique_id": "pp1234",
    "unique_id_type": "netid",
    "rfid": "12245556890478",
 },
{
    "unique_id": "aqe123",
    "unique_id_type": "netid",
    "rfid": "12234556890478",
 }
] 

sample2.json

[
 {
 "mailing_state": "New York",
  "mobile_phone_number": "(982) 2541212",
  "netid": "pp1234",
  "netid_reachable": "Y",
 },
 {
 "mailing_state": "New York",
  "mobile_phone_number": "(982) 5551212",
  "netid": "aqe123",
  "netid_reachable": "Y",
 }
] 

我希望输出看起来像:

results.json

 [
      {
        "unique_id": "pp1234",
        "unique_id_type": "netid",
        "rfid": "12245556890478",
        "mailing_state": "New York",
        "mobile_phone_number": "(982) 2541212",
        "netid_reachable": "Y",
     },
     {
        "unique_id": "aqe123",
        "unique_id_type": "netid",
        "rfid": "12234556890478",
        "mailing_state": "New York",
        "mobile_phone_number": "(982) 5551212",
        "netid_reachable": "Y",
    }
]

结果的顺序无关紧要,只要记录是根据 netid/unique_id 键合并的。如有必要,我愿意使用 jq 以外的东西。提前致谢。

样本输入文件得到更正后,以下调用应该可以解决问题:

jq --argfile uid sample1.json '
  ($uid | INDEX(.unique_id)) as $dict
  | map( $dict[.netid] + del(.netid) )
' sample2.json

如果您不想使用 --argfile 因为它已被弃用,您可以(例如)使用 --slurpfile 并将 jq 程序中的 $uid 更改为 $uid[0]