【问题标题】:jq: missing key in front of the value, only value is printingjq:值前面缺少键,只有值正在打印
【发布时间】:2021-12-29 18:25:23
【问题描述】:

这是我从我的 api 中提取的原始数据:

{
  "observations": [
    {
      "winddir": 292,
      "humidity": 92,
      "qcStatus": 1,
      "imperial": {
        "temp": 20,
        "heatIndex": 20,
        "dewpt": 40,
        "windChill": 20,
        "windSpeed": 3, 
        "windGust": 3,
        "pressure": 29.71,
        "precipRate": 0,
        "precipTotal": 0.01,
        "elev": 1905
      }
    }
  ]
}

这是我运行的命令:

curl -s 'https://api.myawesomeapidata.com' | jq -r '.observations[].winddir, .observations[].humidity, .observations[].imperial.temp'

这是输出:

292
92
20

这是我想要的输出:

Wind Direction: 292
Humidity: 92
Temperature: 20

但如果这是输出就好了:

winddir: 292
humidity: 92
temp: 20

如您所见,我希望键出现在值的前面。最好允许我在打印之前更改键名(风向),但我也可以使用原始键名(winddir)。

【问题讨论】:

    标签: json curl jq


    【解决方案1】:

    使用String interpolation试试这个

    … | jq -r '.observations[]
      | "Wind Direction: \(.winddir)"
      , "Humidity: \(.humidity)"
      , "Temperature: \(.imperial.temp)"
    ' 
    
    Wind Direction: 292
    Humidity: 92
    Temperature: 20
    

    Demo

    【讨论】:

      【解决方案2】:

      然而你可以通过使用

      来保留原来的键名
      jq -r '.observations[] | {winddir},{humidity},(.imperial| {temp})| "\(keys[]) : \(.[])"'
      

      结果

      winddir : 292
      humidity : 92
      temp : 20
      

      Demo

      【讨论】:

      • 你也可以用字符串插值来简化后面的部分:.observations[] | {winddir}, {humidity}, (.imperial | {temp}) | "\(keys[]): \(.[])".
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2020-12-18
      • 2022-06-30
      • 1970-01-01
      • 2019-01-04
      • 2021-04-13
      • 2016-03-17
      相关资源
      最近更新 更多