gpt4 book ai didi

json - 使用 jq 将两个数组合并为一个对象

转载 作者:行者123 更新时间:2023-12-03 06:42:11 28 4
gpt4 key购买 nike

我正在尝试使用 jq 将 NOAA 数据源解析为我需要的值:

http://forecast.weather.gov/MapClick.php?FcstType=json&lat=39.56&lon=-104.85

我能够(单独)提取我想要组合的两个数组:

$ cat noaa.json | jq .time.startPeriodName
[
"Today",
"Tonight",
"Friday",
"Friday Night",
"Saturday",
"Saturday Night",
"Sunday",
"Sunday Night",
"Monday",
"Monday Night",
"Tuesday",
"Tuesday Night",
"Wednesday"
]

$ cat noaa.json | jq .data.weather
[
"Mostly Sunny",
"Mostly Cloudy",
"Mostly Sunny",
"Partly Cloudy",
"Slight Chance Showers",
"Slight Chance Snow Showers",
"Slight Chance Snow Showers then Mostly Sunny",
"Mostly Clear",
"Mostly Sunny",
"Partly Cloudy",
"Mostly Sunny",
"Partly Cloudy",
"Mostly Sunny"
]

我想将两个数组组合成一个对象,如下所示:

{ 
"Today": "Mostly Sunny",
"Tonight": "Mostly Cloudy",
...
"Wednesday": "Mostly Sunny"
}

如果有人能指出我正确的方向,我将不胜感激。我觉得答案可能在 map 运算符中,但我一直无法弄清楚。

最佳答案

是的,map 是一个不错的选择。这里的关键是将它与 transpose/0 一起使用,它可以像“zip”函数一样使用:

 [.time.startPeriodName, .data.weather]
| transpose
| map( {(.[0]): .[1]})

输出开始如下:

[
{
"Today": "Mostly Sunny"
},
{
"Tonight": "Mostly Cloudy"
},
...

因此,要生成单个 JSON 对象,只需将 add 过滤器添加到管道即可。

关于json - 使用 jq 将两个数组合并为一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41045659/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com