简体   繁体   English

使用JQ的多个过滤器

[英]Multiple filters using JQ

My boss wants our team to use JQ to parse JSON files. 我的老板希望我们的团队使用JQ来解析JSON文件。 An app I use produces JSON that I need to transform. 我使用的应用程序生成我需要转换的JSON。 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"
        }
    ]
}

Using JQ, when I execute this: 使用JQ,当我执行这个时:

cat json.txt | jq -r '.Collections[].OptionGroups[].OptionGroupName, .Collections[].InstanceIdentifier, .Collections[].Version'

I get this output: 我得到这个输出:

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. 如果你不小心,你可能会得到意想不到的结果。

I would approach this as converting to CSV (but using a different delimiter, a tab). 我会将其视为转换为CSV(但使用不同的分隔符,选项卡)。

First convert the data to what will be your rows. 首先将数据转换为您的行。

.Collections[] | { InstanceIdentifier, Version } + (.OptionGroups[] | { OptionGroupName })

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. 不要将数组传递给@csv过滤器,只需将它们与选项卡连接即可。

[ .OptionGroupName, .InstanceIdentifier, .Version ] | join("\t")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM