1

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

0

1 Answer 1

5

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

4 Comments

this is probably exactly what I need. but I keep getting a syntax error. "unexpected token <" done < <(jq -r '@text "\(.id) \(.name)"' <<<"$json_string")
Make sure you're using bash, not sh
@veilig, you tagged your question bash, so I gave you an answer that works with bash. If you need an answer that works with /bin/sh, that's a (sligthly) different question; adjust the tags and I'll change the answer accordingly.
my bad - was my mistake.

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.