Search code examples
jquerybashshjq

jq command to check if a json array response has particular user name and state as approved using shell script


I have a json array response below,

[
    {
        "user": {
            "login": "TOM",
        },
        "body": "",
        "state": "APPROVED",
    },
    {
        "user": {
            "login": "JERRY",
        },
        "body": "",
        "state": "APPROVED",
    },
    {
        "user": {
            "login": "ANDY",
        },
        "body": "",
        "state": "REJECTED",
    }
]

I am working on code to check if only when user Jerry exists and has state APPROVED I should set a variable value as true else it should be false.

In above case I should get true and in either of the below cases it should be false

[
    {
        "user": {
            "login": "TOM",
        },
        "body": "",
        "state": "APPROVED",
    },
    {
        "user": {
            "login": "JERRY",
        },
        "body": "",
        "state": "REJECTED",
    },
    {
        "user": {
            "login": "ANDY",
        },
        "body": "",
        "state": "REJECTED",
    }
]

or

[
    {
        "user": {
            "login": "TOM",
        },
        "body": "",
        "state": "APPROVED",
    },
    {
        "user": {
            "login": "ANDY",
        },
        "body": "",
        "state": "REJECTED",
    }
]

I tried below code but I am not able to address both the condition

hasJerry = false
if [ (jq -r '.[].user.login | index("JTHOM949")') && (jq -r '.[].state' == "APPROVED") ]; then

    hasJerry = true

fi

can someone help me to fix this script.


Solution

  • You can have jq output true or false, thus set the variable directly. Within jq, you can use any to find "at least one item" that matches your criteria.

    hasJerry="$(jq 'any(.user.login == "JERRY" and .state == "APPROVED")' input.json)"
    

    Demo

    Note that your Bash script has errors (e.g. whitespace around = with the variable assignment), as does your (sample) JSON input (e.g. commas after the last field in an object). Please correct them first.