veilig
veilig

Reputation: 5135

iterate json into bash variable

If I have a json string in a bash script, how could I convert that into an array?

{ "name": "foo", "id": "123" } { "name": "bar", "id": "456" }

what I want is to be prompted w/ the name, and that tells me what ID (into a variable) that I need to use.

something like

pick your poison:
1) foo
2) bar
#?

If I select 1, then id 123 would go into variable X, else if I select 2 then id 456 would go into variable X

Upvotes: 1

Views: 796

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295278

One of the better approaches is to read the data in question into an associative array -- here, using jq for parsing.

declare -A data=( )
while IFS= read -r id name; do
  data[$id]=$name
done < <(jq -r '@text "\(.id) \(.name)"' <<<"$json_string")

Given this, you can then handle your menu:

echo "Pick your poison:"
for id in "${!data[@]}"; do
  name=${data[$id]}
  printf '%d) %s\n' "$id" "$name"
done
read -p '#?' selection
echo "User selected ${data[$selection]}"

Upvotes: 5

Related Questions