Galet
Galet

Reputation: 6269

How to loop a json keys result from bash script

input.json:-

{
"menu": {
  "id": "file",
  "value": "File",
  "user": {
    "address": "USA",
    "email": "[email protected]"
  }
}
}

Command:-

result=$(cat input.json | jq -r '.menu | keys[]')

Result:-

id
value
user

Loop through result:-

for type in "${result[@]}"
do
    echo "--$type--"
done

Output:-

--id
value
user--

I want to do process the keys values in a loop. When I do the above, It result as a single string.

How can I do a loop with json keys result in bash script?

Upvotes: 5

Views: 9432

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 184965

The canonical way :

file='input.json'
cat "$file" | jq -r '.menu | keys[]' | 
while IFS= read -r value; do
    echo "$value"
done

bash faq #1


But you seems to want an array, so the syntax is (missing parentheses) :

file='input.json'

result=( $(cat "$file" | jq -r '.menu | keys[]') )

for type in "${result[@]}"; do
    echo "--$type--"
done

Output:

--id--
--value--
--user--

Upvotes: 8

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Using bash to just print an object keys from JSON data is redundant.
Jq is able to handle it by itself. Use the following simple jq solution:

jq -r '.menu | keys_unsorted[] | "--"+ . +"--"' input.json

The output:

--id--
--value--
--user--

Upvotes: 2

Related Questions