我正在尝试使用 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"
}
答案1
您的curl
命令查询两个主机。每个都会返回一个 JSON 文档。 jq -s
会将它们添加在一起作为数组中的两个条目。要获取第一个条目(即您作为预期输出呈现的内容),只需从 请求first
(或.[0]
)jq
,如
curl -s ipinfo.io 'api.ipify.org/?format=json' | jq -s 'first'
或者从一开始就使用第一个主机:
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
.
答案2
echo '
[
{
"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": "127.0.0.1",
"country": "UK",
"additional": "added Value"
}
]' | jq "add"
结果
{
"ip": "127.0.0.1",
"hostname": "businessproservices.com",
"city": "London",
"region": "England",
"country": "UK",
"loc": "51.5142,-0.0931",
"postal": "EC2V",
"org": "AS63949 Linode, LLC",
"additional": "added Value"
}```