如何使用jq在JSON文件中筛选同时含指定形容词的条目
使用jq筛选同时包含指定形容词的条目
假设你的JSON文件名为words.json,直接在终端执行以下命令即可找出同时包含"fluffy"和"small"形容词的条目:
jq '.content[] | select(any(.adjectives[]; .adjective == "fluffy") and any(.adjectives[]; .adjective == "small"))' words.json
命令解释
.content[]:遍历JSON顶层content数组中的每一个对象select(...):只保留满足括号内条件的对象any(.adjectives[]; .adjective == "fluffy"):检查当前对象的adjectives数组里,是否存在至少一个元素的adjective字段为"fluffy"and:要求前后两个条件必须同时成立any(.adjectives[]; .adjective == "small"):检查当前对象的adjectives数组里,是否存在至少一个元素的adjective字段为"small"
输出结果
执行命令后,会得到符合条件的完整条目:
{ "word": "cat", "adjectives": [ { "type": "textile", "adjective": "fluffy" }, { "type": "visual", "adjective": "small" } ] }
仅输出单词
如果只需要提取word字段的值,修改命令如下:
jq '.content[] | select(any(.adjectives[]; .adjective == "fluffy") and any(.adjectives[]; .adjective == "small")) | .word' words.json
输出结果:
"cat"
内容的提问来源于stack exchange,提问作者The Gaming Weirdo
相关产品推荐
相关产品推荐

