使用jq将两个数组合并为一个对象 [英] Merge two arrays into a single object with jq

查看:303
本文介绍了使用jq将两个数组合并为一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jq将NOAA数据供稿解析为所需的值:

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"
}

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

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.

推荐答案

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

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]})

输出开始如下:

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

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

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

这篇关于使用jq将两个数组合并为一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆