使用JQ的多个过滤器 [英] Multiple filters using JQ
问题描述
我的老板希望我们的团队使用JQ解析JSON文件.我使用的应用会生成需要转换的JSON.我有一个看起来像这样的文件:
My boss wants our team to use JQ to parse JSON files. An app I use produces JSON that I need to transform. I have a file that looks like this:
{
"Collections": [
{
"OptionGroups": [
{
"OptionGroupName": "Test1",
"Status": "in-sync"
}
],
"Version": "3.4.25",
"InstanceIdentifier": "Dev1"
},
{
"OptionGroups": [
{
"OptionGroupName": "Test2",
"Status": "in-sync"
}
],
"Version": "3.4.22",
"InstanceIdentifier": "Dev2"
}
]
}
在执行此操作时使用JQ:
Using JQ, when I execute this:
cat json.txt | jq -r '.Collections[].OptionGroups[].OptionGroupName, .Collections[].InstanceIdentifier, .Collections[].Version'
我得到以下输出:
Test1
Test2
Dev1
Dev2
3.4.25
3.4.22
我如何获得看起来像这样的输出:
How do I get output that looks something like this:
Test1 Dev1 3.4.25
Test2 Dev2 3.4.22
推荐答案
在单个表达式中使用使用多个[]
的过滤器时,请务必谨慎.如果不小心,可能会得到意想不到的结果.
Always proceed with caution when using filters that uses multiple []
in a single expression. You may get unexpected results if you aren't careful.
我将其转换为CSV(但使用其他定界符,制表符).
I would approach this as converting to CSV (but using a different delimiter, a tab).
首先将数据转换为行.
.Collections[] | { InstanceIdentifier, Version } + (.OptionGroups[] | { OptionGroupName })
有了这些新对象,您可以建立行值的数组并写出该行.不必将数组传递给@csv
过滤器,只需将它们与制表符连接即可.
With these new objects, you can build up arrays of the row values and write out the row. Instead of passing the arrays to the @csv
filter, just join them with tabs.
[ .OptionGroupName, .InstanceIdentifier, .Version ] | join("\t")
这篇关于使用JQ的多个过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!