spacecodeur
spacecodeur

Reputation: 2406

JSON file parsing in linux with JQ, select some elements depending on value contained in a specific element

I'm a new jq user and I have some difficult to find the good way for my problem.

I have this sample json file :

{
    "one":"one_value",
    "two": [
        { // sub structure 0
            "aa" : [
                "aa_value_0"
            ],
            "ab" : { ... },
            "ac" : [
                "ac_value_0"
            ] 
        },
        { // sub structure 1
            "aa": [
                "aa_value_1"
            ],
            "ab": {
                "aba": [
                    "aba_value_1"
                ],
                "abb": [
                    "tototatatiti"
                ],
                "abc": [
                    "abc_value_1"
                ]
            },
            "ac": [
                "ac_value_1"
            ]
        },
        { // sub structure 2
            "aa" : ...
            ...
        },
        ...
        { // sub structure x
            "aa" : ...
            ...
        }
    ]
}

I have an array named "two" who contains several sub structures (sub structure 0, sub structure 1, sub structure 2, ..., sub structure x). I want select the 'ac' and 'aa' values where ab.abb key (in the same sub structure) contains a specific word. All sub structures have the same structure.

In my example, if I search the word "tata", I must obtain the values "aa_value_1" and "ac_value_1" because in the sub structure "1", the ab.abb field contains the word "tata" (tototatatiti)

How can I do that ? Thank you :)

Upvotes: 0

Views: 160

Answers (1)

peak
peak

Reputation: 116957

The requirements are not entirely clear in several respects, but the following query matches the description and produces the two values that it should, assuming the example input has been modified to become valid JSON:

.two[]
| select( .ab.abb | type == "array")
| select( .ab.abb[] | test("tata") )
| [ .ac[],.aa[] ]

(You wouldn't need the second line above if .two is as regular as stated. Also, if your jq does not have test/1, then you could upgrade or use index/1 instead.)

With the given input, after rectification, invocation of jq with the -c option produces:

["ac_value_1","aa_value_1"]

Upvotes: 1

Related Questions