I have a json-file with keys and values that I would like to add to a bash array, but I cannot make it work.
1. Creating JSON-file with data
# JSON file
echo '{"persons": [{"name":"John", "age":30, "car":"big"}, {"name":"Alice", "age":29, "car":"big"}]}' > my.json
2. Iterating over Name and Age
# Looping over JSON
jq -c '.persons[]' my.json | while read p;
do
name=$(echo $p | jq -r '.name')
age=$(echo $p | jq -r '.age')
echo "Name: $name"
echo "Age: $age"
done
Names and ages are printed out as expected.
3. Manually adding Name and Age to Array
# Creating array and adding elements
declare -A mylookup
key="James"
value="31"
mylookup[$key]=$value
4. Checking if values were added
for key in "${!mylookup[@]}"
do
echo "Key: $key"
echo "Value: ${lookup[$value]}"
done
I oddly only shows the Key correctly
5. Adding Name and Age to Array in loop
# Creating array and adding elements
declare -A mylookup
jq -c '.persons[]' my.json | while read p;
do
name=$(echo $p | jq -r '.name')
age=$(echo $p | jq -r '.age')
mylookup[$name]=$age
done
6. Printing out keys and values in Array
Now I check what was added to the array.
for key in "${!mylookup[@]}"
do
echo "Key: $key"
echo "Value: ${lookup[$value]}"
done
Nothing is printed out..... where am I failing? I suspect something is going wrong when I am adding the keys and values to the array, but I cannot find out what.