Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple filters using JQ

Tags:

json

filter

jq

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"
        }
    ]
}

Using JQ, when I execute this:

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
like image 920
jago Avatar asked Jun 10 '15 22:06

jago


1 Answers

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).

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.

[ .OptionGroupName, .InstanceIdentifier, .Version ] | join("\t")
like image 63
Jeff Mercado Avatar answered Sep 29 '22 19:09

Jeff Mercado