Merge two arrays into a single object with jq

我的梦境 提交于 2020-05-13 18:56:06

问题


I'm trying to use jq to parse a NOAA data feed into just the values I need:

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

I'm able to (separately) extract the two arrays I'm looking to combine:

$ 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"
]

I'd like to combine the two arrays together into a single object like this:

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

I'd be grateful if someone could point me in the right direction. I feel like the answer is probably in the map operator, but I haven't been able to figure it out.


回答1:


Yes, map is a good way to go. The key here is to use it with transpose/0, which can be used as though it were a "zip" function:

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

The output begins as follows:

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

So, to produce a single JSON object, simply add the add filter to the pipeline.



来源:https://stackoverflow.com/questions/41045659/merge-two-arrays-into-a-single-object-with-jq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!