首页 > 解决方案 > 使用 jq 获取 json 中匹配元素之后/之前的元素

问题描述

假设我在 jq 命令中有以下 json 输入:

[
  {"type":"dog",  "set":"foo"},
  {"type":"bird", "set":"bar"},
  {"type":"cat",  "set":"blaz"},
  {"type":"fish", "set":"mor"}
]

我知道这个数组中有一个元素type是“鸟”,在这种情况下是第二个元素。但我想要它的下一个(或上一个)兄弟,即它之后(之前)的元素,在这种情况下,是第三个(第一个)元素。我怎样才能在jq中得到它?

另外,我还有一个问题:如果匹配的元素(即type我知道其值的元素)是数组中的最后一个,我希望它获得第一个作为下一个(即循环遍历数组)而不是什么都不返回。匹配的元素是否是第一个相同(然后我想获取最后一个元素)。

标签: jsonjq

解决方案


为了具体起见,假设您想将(before, focus, after)三元组提取为一个数组,beforeafter按照描述的方式环绕。为简单起见,我们还假设源数组的长度至少为 2。

接下来,为了便于阐述和理解,我们将定义一个辅助函数来提取这三个项目:

# $i is assumed to be a valid index into the input array,
# which is assumed to be of length at least 2
def triple($i):
  if $i == 0 then [last] + .[0:2]
  elif $i == (length-1) then .[$i-1: $i+2] + [first]
  else .[$i-1: $i+2]
  end;

现在我们只需要找到索引并使用它:

(map(.type) | index("bird")) as $i
| if $i then triple($i) else empty end

使用这种方法,可以很容易地获得其他变体。


推荐阅读