我有 2 個 json 檔案,我希望相互比較,最終得到的檔案只有第二個檔案中的唯一物件。唯一物件不是由完整物件決定的,而是由其中一個名為 的鍵的值決定的Car ID。下面是一個 json 檔案示例,可以更好地解釋這一點:
檔案1.json:
{
"User Data": [
{"First Name": "Tony", "Last Name": "Evans", "DOB": "1987-02-01", "Car ID": "UJ928JD9"},
{"First Name": "John", "Last Name": "Smith", "DOB": "1972-11-27", "Car ID": "UJ235UW8"},
{"First Name": "Kirsty", "Last Name": "Morgan", "DOB": "1991-06-08", "Car ID": "UJ424KL2"},
...
]
}
檔案2.json
{
"User Data": [
{"First Name": "Harry", "Last Name": "Jones", "DOB": "1983-03-09", "Car ID": "UJ928JD9"},
{"First Name": "Jeremy", "Last Name": "Blake", "DOB": "1965-09-21", "Car ID": "UJ345IE2"},
{"First Name": "Jason", "Last Name": "Roberts", "DOB": "1972-10-18", "Car ID": "UJ424KL2"},
...
]
}
在上面的示例中,2 行的 Car ID 是相同的,因此應該只保留第二個檔案中的第二個物件,如下所示:
{
"User Data": [
{"First Name": "Jeremy", "Last Name": "Blake", "DOB": "1965-09-21", "Car ID": "UJ345IE2"}
]
}
uj5u.com熱心網友回復:
使用 將兩個檔案作為變數讀入--argfile,然后將map兩者都讀入它們的Car ID,然后從第二個陣列中減去第一個陣列,從而得到Car ID要保留的s陣列,最后使用select第二個輸入檔案中正確元素的鍵。
jq -n \
--argfile file1 file1.json \
--argfile file2 file2.json \
'
# Take both input files and create an array $ids with all
# Car IDs from the second file that are not part of the first one
[ $file1, $file2 ]
| map(.["User Data"] | map(.["Car ID"]))
| (.[1] - .[0]) as $ids
# Take the second input file and select only those entries
# whose Car ID is part of the previously stored array of Car IDs
| $file2
| .["User Data"] |= map(select(.["Car ID"] == $ids[]))
'
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/317371.html
下一篇:Unix將時間格式轉換為整數值
