parse json and put in array

Viewed 37

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

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")
Related