如何使用jq将json格式化为csv?

问题描述 投票:0回答:1

我尝试将此 json 数据格式化为 CSV 格式,但出现此错误:

error (at <stdin>:0): Cannot index array with string "time". 
这是我的 json 数据的简短版本:

{
  "latitude": 52.52,
  "longitude": 13.419998,
  "generationtime_ms": 0.23293495178222656,
  "utc_offset_seconds": 7200,
  "timezone": "Europe/Berlin",
  "timezone_abbreviation": "CEST",
  "elevation": 38.0,
  "daily_units": {
    "time": "iso8601",
    "weather_code": "wmo code",
    "temperature_2m_max": "°F",
    "temperature_2m_min": "°F",
    "precipitation_probability_max": "%"
  },
  "daily": {
    "time": [
      "2024-10-13",
      "2024-10-14"
    ],
    "weather_code": [
      80,
      61
    ],
    "temperature_2m_max": [
      52.7,
      53.1
    ],
    "temperature_2m_min": [
      48.6,
      43.7
    ],
    "precipitation_probability_max": [
      100,
      10
    ]
  }
}

我希望它的格式如下:

time,weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max
2024-10-13,80,52.7,48.6,100
2024-10-14,61,53.1,43.7,10

这是我写的命令,但我收到错误

jq: error (at <stdin>:0): Cannot index array with string "time"
。如果我删除所有以前的字段,每个字段也会发生这种情况。

curl -s "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max&temperature_unit=fahrenheit&wind_speed_unit=mph&precipitation_unit=inch&timezone=auto&forecast_days=14" | 

jq -r '
  [
    "date", "weather_code", "temperature_2m_max", "temperature_2m_min", "precipitation_probability_max"
  ],
  .daily |
  [
    .time[],
    .weather_code[],
    .temperature_2m_max[],
    .temperature_2m_min[],
    .precipitation_probability_max[]
  ]
  | @csv
'

我尝试将“时间”字段更改为 Unix 时间戳,但我仍然不确定如何让它工作,因为它会抛出相同的错误。

json string bash curl jq
1个回答
0
投票

您需要

transpose
功能:

curl -s "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max&temperature_unit=fahrenheit&wind_speed_unit=mph&precipitation_unit=inch&timezone=auto&forecast_days=14" | 
jq -r '([ "date", "weather_code", "temperature_2m_max", "temperature_2m_min", "precipitation_probability_max"],
        ([.daily[]] | transpose[])
       ) | @csv'
© www.soinside.com 2019 - 2024. All rights reserved.