簡體   English   中英

使用jq根據鍵值合並兩個json值

[英]using jq to merge two json values based on key value

我有兩個 json 文件,我想根據一個鍵的值合並它們。 兩個 json 文件中的鍵名不同,但值相同。 我正在使用 jq 來嘗試完成這項工作。 我發現的大多數示例都基於鍵名而不是值進行合並。

示例1.json

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

示例2.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",
 }
] 

我希望輸出看起來像:

結果.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和變化$uid在JQ程序$uid[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM