我有两个 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]
。
关于json - 使用jq根据键值合并两个json值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63819013/