使用JQ使用其父键提取某些数组元素
我想知道如何使用 jq 从 .json 文件中提取模式
echo '{"parts": [{"name":"core","items":"garbage with ITEM1 ITEM2 and more"},{"name":"misc","items":"ITEM3 ITEM4 ITEM5 bla bla"} ]}' | jq '.parts | .[] | .items |=split(" ")'
{
"name": "core",
"items": [
"garbage",
"with",
"ITEM1",
"ITEM2",
"and",
"more"
]
}
{
"name": "misc",
"items": [
"ITEM3",
"ITEM4",
"ITEM5",
"bla",
"bla"
]
}
,我认为在拆分项目时,但我不知道如何提取每个 ITEMx。
我想获得这个输出:
{ "core","ITEM1" }
{ "core","ITEM2" }
{ "misc","ITEM3" }
{ "misc","ITEM4" }
{ "misc","ITEM5" }
I would like to know how to use jq to extract patterns from a .json file
echo '{"parts": [{"name":"core","items":"garbage with ITEM1 ITEM2 and more"},{"name":"misc","items":"ITEM3 ITEM4 ITEM5 bla bla"} ]}' | jq '.parts | .[] | .items |=split(" ")'
{
"name": "core",
"items": [
"garbage",
"with",
"ITEM1",
"ITEM2",
"and",
"more"
]
}
{
"name": "misc",
"items": [
"ITEM3",
"ITEM4",
"ITEM5",
"bla",
"bla"
]
}
I think in splitting the items, but I don't know how to extract each ITEMx.
I want to obtain this output:
{ "core","ITEM1" }
{ "core","ITEM2" }
{ "misc","ITEM3" }
{ "misc","ITEM4" }
{ "misc","ITEM5" }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所需的输出不是有效的JSON。
您是否要在
.Name
字段的值下形成一个数组?demo
或您是否希望每个单词形成一个单独的对象?
demo
仅捕获与Regex
iteg> Item \ d+d+
的单词采用扫描
函数而不是拆分:demo
Your desired output is not valid JSON.
Do you want the words form an array under the value of the
.name
field?Demo
Or do you want each word to form a separate object?
Demo
To only capture words that match the regex
ITEM\d+
, you could employ thescan
function instead of splitting:Demo
基于您的尝试,我们可以尝试:
这会生成一个对象流,例如
{"core":"ITEM1"}
。如果您确实想要 Q 中显示的非 JSON 输出,那么添加额外的步骤就很容易了。Building on your attempt, we could try:
This produces a stream of objects such as
{"core":"ITEM1"}
. If you really want the non-JSON output shown in the Q, it's easy enough to add the additional step.