使用jq

时间:2016-12-08 17:45:27

标签: json merge key jq

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

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运算符中,但我还没有弄明白。

1 个答案:

答案 0 :(得分:6)

是的,map是一个很好的方法。这里的关键是将它与transpose/0一起使用,它可以像使用“zip”函数一样使用:

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

输出开始如下:

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

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