1

I want to use jq to return the RuleArn value if the following condition matches i.e. .[].Conditions[].Values[] has an element that matches app.fantastic.com

My JSON array:

[
    {
        "Conditions": [
            {
                "Field": "http-header",
                "HttpHeaderConfig": {
                    "Values": [
                        "dark"
                    ],
                    "HttpHeaderName": "Environment"
                }
            },
            {
                "Values": [
                    "app.fantastic.com"
                ],
                "Field": "host-header",
                "HostHeaderConfig": {
                    "Values": [
                        "app.fantastic.com"
                    ]
                }
            }
        ],
        "IsDefault": false,
        "Priority": "3",
        "RuleArn": "iwantthisvalue"
    }
]

I've tried these:

| jq -r '.[] | select(.Conditions[].Values[]=="app.fantastic.com")'

and

| jq -r '.[] | select(.Conditions[].Values[] | has("app.fantastic.com"))'

I get the following error:

jq: error (at :144): Cannot index array with string "Conditions"

And with this:

| jq '.[].Conditions[].Values | index ("app.fantastic.com") == 0 | .RuleArn'

This is the error I get:

jq: error (at :47): Cannot index boolean with string "RuleArn"

Note: I do not want a solution using --query of AWS cli as I use --query already to get a smaller JSON payload which I want to filter further using jq.

1 Answer 1

3

The root of the difficulty you are running into is that the problem statement is improper: .[].Conditions[].Values[] does not correspond to your JSON.

Using jq 1.5 or later, you could use the following filter:

.[]
| first(select(.Conditions | .. | objects
               | select(has("Values") and 
                        (.Values|index("app.fantastic.com")))))
| .RuleArn

Since .Values occurs in several places, it's not clear what the precise requirements are, but you might also wish to consider:

.[]
| select(.Conditions[].Values? | index("app.fantastic.com"))
| .RuleArn

or (less efficiently, but it works with jq 1.4 or later):

.[]
| select(.Conditions[].Values[]? == "app.fantastic.com")
| .RuleArn
Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks Peak, what does this notation mean? | .. | objects
Unfortunately all 3 solutions give me the same error jq: error (at <stdin>:144): Cannot index array with string "Conditions"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.