迭代对象中的项

时间:2015-12-22 23:08:53

标签: json jq

我正在尝试解析其中一个es集群的json输出以收集过滤器缓存统计信息,并希望使用Jq来执行此操作。以下是curl命令的输出:

{
  "_shards": {
    "total": 5662,
    "successful": 5662,
    "failed": 0
  },
  "_all": {
    "primaries": {
      "filter_cache": {
        "memory_size": "32.8gb",
        "memory_size_in_bytes": 35245081088,
        "evictions": 31347095
      }
    },
    "total": {
      "filter_cache": {
        "memory_size": "94.3gb",
        "memory_size_in_bytes": 101307321504,
        "evictions": 79329152
      }
    }
  },
  "indices": {
    "oreserverdk04180047": {
      "primaries": {
        "filter_cache": {
          "memory_size": "0b",
          "memory_size_in_bytes": 0,
          "evictions": 11
        }
      },
      "total": {
        "filter_cache": {
          "memory_size": "0b",
          "memory_size_in_bytes": 0,
          "evictions": 132
        }
      }
    },
    "janbe10200002": {
      "primaries": {
        "filter_cache": {
          "memory_size": "0b",
          "memory_size_in_bytes": 0,
          "evictions": 88
        }
      },
      "total": {
        "filter_cache": {
          "memory_size": "0b",
          "memory_size_in_bytes": 0,
          "evictions": 119
        }
      }
    }
  }
}

基本上我想让输出看起来像这样:

oreserverdk04180047 0b
janbe10200002 0b

我只想要索引的名称和来自" total"的memory_size列。如果我通过硬编码索引名称来运行它,我可以得到它:

jq '. | {memory_size: .indices.janbe10200002.total.filter_cache.memory_size}'

但是我希望通过使用某种通配符来迭代索引名称。

2 个答案:

答案 0 :(得分:0)

jq -r  '
  .indices
  | to_entries[]
  | "\(.key) \(.value.total.filter_cache.memory_size)"
' input.json

输出:

oreserverdk04180047 0b
janbe10200002 0b

答案 1 :(得分:0)

以下是使用 foreach

的解决方案
  .indices
| foreach keys[] as $k (
      .
    ; .
    ; "\($k) \(.[$k].total.filter_cache.memory_size)"
  )

编辑:我现在意识到foreach E as $X (.; .; R)形式的过滤器几乎总是被重写为E as $X | R所以上面的内容实际上就是

  .indices
| keys[] as $k
| "\($k) \(.[$k].total.filter_cache.memory_size)"