skip to Main Content

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.

2

Answers


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

    Login or Signup to reply.
  2. Instead of returning the raw True or False strings, you could test the return status:

    #!/usr/bin/env sh
    
    user=$1
    
    while [ -z "$user" ]; do
      printf 'Enter user: ' 
      read -r user
      printf \n
    done
    
    if jq -e --arg user "$user" 
      '
    .users | 
    any(
      .user.login == ($user | ascii_upcase) and
      .state == "APPROVED"
    )
    ' input.json > /dev/null
    then
      printf '%s is approved!n' "$user"
    else
      printf 'Non-aproved user %s!n' "$user"
    fi
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search