-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"
}
F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137
theAnonymous
  • 1,701
  • 2
  • 28
  • 62
  • 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. – chepner Sep 08 '21 at 13:08
  • Need to do from associative array to json map and back. – theAnonymous Sep 08 '21 at 13:37
  • So again, what does the value you assign to `json` have to do with this? – chepner Sep 08 '21 at 13:38

1 Answers1

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
Dfaure
  • 564
  • 7
  • 26