-1

I'm having a JSON file groups.json which is having data in below format -

[
{ "key" : "value" },
{ "key" : "value" },
{ "key" : "value" }
]

I need these key value pairs to a bash array of strings like this -

bashArray = [ { "key" : "value" }  { "key" : "value" }  { "key  : "value" } ]

How can I achieve this on Bash3.x?

1
  • Please add your desired output for declare -p bashArray to your question. Commented Jan 2, 2021 at 7:52

1 Answer 1

2

With modern versions of bash, you'd simply use mapfile in conjunction with the -c option of jq (as illustrated in several other SO threads, e.g. Convert a JSON array to a bash array of strings)

With older versions of bash, you would still use the -c option but would build up the array one item at a time, along the lines of:

while read -r line ; do 
  ary+=("$line")
done < <(jq -c .......)

Example

#!/bin/bash
function json {
    cat<<EOF
[
  { "key" : "value1" },
  { "key" : "value2" },
  { "key" : "value3" }
]
EOF
}

while read -r line ; do 
  ary+=("$line")
done < <(json | jq -c .[])

printf "%s\n" "${ary[@]}"

Output:

{"key":"value1"}
{"key":"value2"}
{"key":"value3"}
Sign up to request clarification or add additional context in comments.

1 Comment

@CharlesDuffy - Tx. Fixed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.