Parsing a nested JSON record present in an array of objects

40 views Asked by At

I want to get down to the values in Wind / Direction. One example (of many) I've tried, [I want to use jq in a bash script]:

cat accuweather_raw | jq ".Wind[].Direction[] | [.Localized]"

Most times I get err cannot index array with string "of some iteration"

Help!

Take this JSON:

[
  {
    "LocalObservationDateTime": "2024-03-27T21:32:00-05:00",
    "EpochTime": 1711593120,
    "WeatherText": "Clear",
    "WeatherIcon": 33,
    "HasPrecipitation": false,
    "PrecipitationType": null,
    "IsDayTime": false,
    "Temperature": {
      "Metric": {
        "Value": 20,
        "Unit": "C",
        "UnitType": 17
      },
      "Imperial": {
        "Value": 68,
        "Unit": "F",
        "UnitType": 18
      }
    },
    "RealFeelTemperature": {
      "Metric": {
        "Value": 17.8,
        "Unit": "C",
        "UnitType": 17,
        "Phrase": "Pleasant"
      },
      "Imperial": {
        "Value": 64,
        "Unit": "F",
        "UnitType": 18,
        "Phrase": "Pleasant"
      }
    },
    "RealFeelTemperatureShade": {
      "Metric": {
        "Value": 17.8,
        "Unit": "C",
        "UnitType": 17,
        "Phrase": "Pleasant"
      },
      "Imperial": {
        "Value": 64,
        "Unit": "F",
        "UnitType": 18,
        "Phrase": "Pleasant"
      }
    },
    "RelativeHumidity": 62,
    "IndoorRelativeHumidity": 63,
    "DewPoint": {
      "Metric": {
        "Value": 12.8,
        "Unit": "C",
        "UnitType": 17
      },
      "Imperial": {
        "Value": 55,
        "Unit": "F",
        "UnitType": 18
      }
    },
    "Wind": {
      "Direction": {
        "Degrees": 90,
        "Localized": "E",
        "English": "E"}, 

... continued

1

There are 1 answers

1
Inian On BEST ANSWER

The filter is not quite correct. You need to do,

.[].Wind.Direction | [.Localized]

Remember you are accessing an array at the top level, so .[] selects the objects within. And Wind is an object and not an array, so just .Wind is needed to access the sub-element .Direction. By doing .Wind[], you can end up with values only part of all the sub-elements, which is not desirable (See Array/Object Value Iterator). But you could still do .[].Wind[] | [.Localized].

But the top level array access is needed.