-1

The example here:

#!/bin/bash

declare -A rep_hostname
rep_hostname=( [test1]='172.1.1.1' [test2]='172.1.1.2' [test3]='172.1.1.3' )

json=$(
        jo members="$(
                jo -a "${rep_hostname[@]}" |
                jq -c 'to_entries | map({ "_id": .key, "host": .value })'
        )"
)

echo "$json"

outputs the following:

{
    "members":[
      {"_id":0,"host":"172.1.1.3:2701"},
      {"_id":1,"host":"172.1.1.2:2701"},
      {"_id":2,"host":"172.1.1.1:2701"}
    ]
}

How to make the following JSON?

{
    "test1":"172.1.1",
    "test2":"172.1.1.2",
    "test3":"172.1.1.3"
}
3
  • 1
    What does the associative array have to do with this? If all you have is the JSON, you can use jq to parse it and produce the desired JSON. If you are starting with the associative array, you don't need to define json in the first place; you can work directly with the array. Commented Sep 8, 2021 at 13:08
  • Need to do from associative array to json map and back. Commented Sep 8, 2021 at 13:37
  • So again, what does the value you assign to json have to do with this? Commented Sep 8, 2021 at 13:38

1 Answer 1

1

Cf. https://unix.stackexchange.com/questions/366581/bash-associative-array-printing

jo $(paste -d= <(printf "%s\n" "${!rep_hostname[@]}") <(printf "%s\n" "${rep_hostname[@]}"))

The printf commands will output associative keys and values by lines, the paste -d= ... will merge the produced lines bound by an = sign and lastly the jo processor will build a JSON from that.

A more iterative equivalent could also be:

for i in "${!rep_hostname[@]}";do printf "%s=%s\n" "$i" "${rep_hostname[$i]}";done | jo
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.