json - 使用 jq 获取 json 中匹配元素之后/之前的元素
问题描述
假设我在 jq 命令中有以下 json 输入:
[
{"type":"dog", "set":"foo"},
{"type":"bird", "set":"bar"},
{"type":"cat", "set":"blaz"},
{"type":"fish", "set":"mor"}
]
我知道这个数组中有一个元素type
是“鸟”,在这种情况下是第二个元素。但我想要它的下一个(或上一个)兄弟,即它之后(之前)的元素,在这种情况下,是第三个(第一个)元素。我怎样才能在jq中得到它?
另外,我还有一个问题:如果匹配的元素(即type
我知道其值的元素)是数组中的最后一个,我希望它获得第一个作为下一个(即循环遍历数组)而不是什么都不返回。匹配的元素是否是第一个相同(然后我想获取最后一个元素)。
解决方案
为了具体起见,假设您想将(before, focus, after)
三元组提取为一个数组,before
并after
按照描述的方式环绕。为简单起见,我们还假设源数组的长度至少为 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
使用这种方法,可以很容易地获得其他变体。
推荐阅读
- android - APK 包中 .properties 文件的用途是什么?
- r - 遍历列并计算满足R中条件的行
- python - 从文本中提取标题
- java - 如何使用 AsyncTask、RecyclerView 和 RecyclerView.Adapter 将手机中的图像获取到 RecyclerView?
- javascript - 当我使用换行符渲染字符串时,ejs 抛出“TypeError:无法在字符串上创建属性 '_locals'”错误
- r - 使用数据透视函数时,我可以返回分散的值的总和吗?
- python - 在上下文管理器函数中使用 Python 记录器
- python - 在 Pandas 中,如何使用数字位置查找列名和行名?
- ethereum - 如何使用 python 为以太坊节点发现构建 ping 消息?
- mysql - 如何将结果网格放置在右上角,即mysql工作台中sql添加的位置?