Json

jq(命令行 JSON 處理器)合併來自 STDIN 的多個 JSON 字元串

  • July 13, 2021

我正在嘗試使用 jq 命令合併來自 STDIN 的兩個不同的 JSON 字元串(使用管道,而不是文件)。這是嘗試的命令:

curl  ipinfo.io api.ipify.org/?format=json 2>/dev/null | jq -s

輸出:

[
 {
   "ip": "139.162.244.103",
   "hostname": "businessproservices.com",
   "city": "London",
   "region": "England",
   "country": "GB",
   "loc": "51.5142,-0.0931",
   "postal": "EC2V",
   "org": "AS63949 Linode, LLC"
 },
 {
   "ip": "139.162.244.103"
 }
]

預期輸出:

{
 "ip": "139.162.244.103",
 "hostname": "businessproservices.com",
 "city": "London",
 "region": "England",
 "country": "GB",
 "loc": "51.5142,-0.0931",
 "postal": "EC2V",
 "org": "AS63949 Linode, LLC"
}

您的curl命令查詢兩個主機。每個都將返回一個 JSON 文件。 jq -s將這些加在一起作為數組中的兩個條目。要獲得第一個條目(這是您作為預期輸出呈現的內容),只需.[0]從請求jq,如

curl -s ipinfo.io 'api.ipify.org/?format=json' | jq -s '.[0]'

或者從一開始就使用第一個主機:

curl ipinfo.io

要實際合併兩個文件,請將jq命令add應用於返回的列表:

curl -s ipinfo.io 'api.ipify.org/?format=json' | jq -s 'add'

請注意,由於 JSON 對像不能包含多個具有相同名稱的鍵,因此任何後面的鍵都將替換等效的早期鍵,因此如果您的jq -s文件是

[
 {
   "ip": "139.162.244.103",
   "hostname": "businessproservices.com",
   "city": "London",
   "region": "England",
   "country": "GB",
   "loc": "51.5142,-0.0931",
   "postal": "EC2V",
   "org": "AS63949 Linode, LLC"
 },
 {
   "ip": "39.62.44.1",
   "country": "UK"
 }
]

那麼這將被合併為

{
 "ip": "39.62.44.1",
 "hostname": "businessproservices.com",
 "city": "London",
 "region": "England",
 "country": "UK",
 "loc": "51.5142,-0.0931",
 "postal": "EC2V",
 "org": "AS63949 Linode, LLC"
}

使用jq -s add時代替jq -s.

引用自:https://unix.stackexchange.com/questions/510065