解析对象数组中存在的嵌套 JSON 记录

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

我想了解风/方向中的值。 我尝试过的一个(很多)例子,[我想在 bash 脚本中使用 jq]:

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

大多数时候我得到错误无法用字符串“某些迭代”索引数组

救命!

获取此 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"}, 

...继续

json jq
1个回答
0
投票

过滤器不太正确。你需要做,

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

请记住,您正在访问顶层的数组,因此

.[]
选择其中的对象。并且
Wind
是一个对象而不是数组,因此只需要
.Wind
即可访问子元素
.Direction
。通过执行
.Wind[]
,您最终可能会得到所有子元素的一部分,这是不可取的(请参阅数组/对象值迭代器)。但你仍然可以做
.[].Wind[] | [.Localized]

但是需要顶层数组访问。

© www.soinside.com 2019 - 2024. All rights reserved.