所以,假设我有一个JSON文件,如下所示:
{
"content": [
{
"word": "cat",
"adjectives": [
{
"type": "textile",
"adjective": "fluffy"
},
{
"type": "visual",
"adjective": "small"
}
]
},
{
"word": "dog",
"adjectives": [
{
"type": "textile",
"adjective": "fluffy"
},
{
"type": "visual",
"adjective": "big"
}
]
},
{
"word": "chocolate",
"adjectives": [
{
"type": "visual",
"adjective": "small"
},
{
"type": "gustatory",
"adjective": "sweet"
}
]
}
]
}
现在,假设我想搜索两个单词。例如;蓬松的";以及";小"这个问题是两个词的形容词都包含小,所以我必须手动搜索哪个词包含蓬松。那么,我该如何更快地做到这一点呢?
换言之,我将如何找到同时具有";蓬松的";以及";"小";
编辑:对不起,新提问者。任何在终端上说的话都是公平的。jq
是一个非常棒的JSON搜索器,因此这是首选,很抱歉造成混淆。我还修复了JSON
命令行解决方案是使用jq:
jq -r '.content[] | select(.adjectives[].adjective == "fluffy") | .word' /pathToJsonFile.json
输出:
cat
你在找这样的东西吗?您需要使用其他编程语言的解决方案吗?
(请注意,您的JSON示例似乎无效(
由于jq现在是公平的游戏(这在后面的评论中才得到澄清(,这里有一个使用jq的解决方案。
首先,将JSON修复为实际有效:
{
"content": [
{
"word": "cat",
"adjectives": [
{
"type": "textile",
"adjective": "fluffy"
},
{
"type": "visual",
"adjective": "small"
}
]
},
{
"word": "dog",
"adjectives": [
{
"type": "textile",
"adjective": "fluffy"
},
{
"type": "visual",
"adjective": "big"
}
]
},
{
"word": "chocolate",
"adjectives": [
{
"type": "visual",
"adjective": "small"
},
{
"type": "gustatory",
"adjective": "sweet"
}
]
}
]
}
然后,下面的jq过滤器返回一个数组,该数组包含包含两个形容词的单词:
.content
| map(
select(
.adjectives as $adj
| all("small","fluffy"; IN($adj[].adjective))
)
| .word
)
如果需要非阵列输出,并且每行只有一个字,则使用.[]
而不是map
(在content
之后或作为最终滤波器(,例如:
jq -r '.content[]
| select(
.adjectives as $adj
| all("small","fluffy"; IN($adj[].adjective))
)
| .word'