5

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?

1
  • using bash is redundant in such case Commented Mar 20, 2018 at 12:45

2 Answers 2

8

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--
Sign up to request clarification or add additional context in comments.

5 Comments

I am getting jq: error: syntax error, unexpected IDENT, expecting $end (Unix shell quoting issues?) at <top-level>, line 1: when executing second approach.
Still I get error in this line result=( $(jq -r '.menu | keys[]' input.json) ) after your updation. Also I want input.json name to be dynamic
result=( $(cat input.json | jq -r '.menu | keys[]') ). this works.
You need to install it (no deps)
Thanks, the only solution actually working for my case !
2

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

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.