Home > Mobile >  jq: missing key in front of the value, only value is printing
jq: missing key in front of the value, only value is printing

Time:12-30

This is the raw data I pull from my 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
      }
    }
  ]
}

This is the command that I run:

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

This is the output:

292
92
20

This is the output I would like:

Wind Direction: 292
Humidity: 92
Temperature: 20

But I would be fine if this were the output:

winddir: 292
humidity: 92
temp: 20

As you can see, I would like the key to appear in front of the value. Preferably allowing me to change the name of the key (Wind Direction) before printing, but I would also be fine with the original key name (winddir).

CodePudding user response:

Try this using String interpolation

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

Demo

CodePudding user response:

Yet you can keep the original key names through use of

jq -r '.observations[] | {winddir},{humidity},(.imperial| {temp})| "\(keys[]) : \(.[])"'

which results

winddir : 292
humidity : 92
temp : 20

Demo

  • Related