1

I am trying to parse a JSON file which looks like this and then trying to store each field in an array, then trying to read it. However, its going in an infinite loop, I think. Anyone knows what I am doing wrong?

#!/bin/bash

test(){
    local file="/Users/f.json"
    if [ -f "$file" ]; then
    echo "present"
    else
        echo "absent"
    fi
    
    #jq . f.json
    
    while read rule; do
        local idd
        local username

    idd=$(jq --raw-output '.id' <<< ${rule})
    username=$(jq --raw-output '.username' <<< ${rule})
    
    #username=$(jq --raw-output '.username')

    done
    
    for (( i=0; i<${#idd[@]}; i++ )); do
        echo "${idd[i]}"
    done
    
}
test

Here is json:

{
      "id": 5679162,
      "username": "ryderw1"
    }
    {
      "id": 5679163,
      "username": "ryderw3"
    }
    {
      "id": 5679164,
      "username": "ryderw4"
    }

My desired o/p should be:

5679162
5679163
5679164
0

1 Answer 1

1

I suggest this to read output from jq to an array.

mapfile -t idd < <(jq '.id' /Users/f.json)
declare -p idd

Output:

declare -a idd=([0]="5679162" [1]="5679163" [2]="5679164")
Sign up to request clarification or add additional context in comments.

Comments

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.