Varun Chandak
Varun Chandak

Reputation: 971

Convert BASH Array to JSON Array

I have a BASH Array as follows:

TEMPARRAY=( "1 A" "2 B" )

I want this array to convert to JSON Array (or Key Value Pair ?), like this:

{
  "Comment": "MX Record for XYZ",
  "Changes": [
    {
      "Action": "CREATE",
      "ResourceRecordSet": {
        "Name": "XYZ",
        "Type": "MX",
        "TTL": 300,
        "ResourceRecords": [
        {
          "Value": "1 A"
        },
        {
          "Value": "2 B"
        }
       ]
      }
    }
  ]
}

USE CASE: I am creating a shell script to add AWS Route53 DNS Records and I am stuck at specifying multiple values for MX records. If I update the MX records, it get replaced with a newer one.

Sample Code from my script:

      if [[ "$MXCOUNT" -gt "1" ]]; then
        TEMPARRAY=( "$(grep -i MX  "$DNSFILE" | cut -d, -f3)" )
        for i in "${TEMPARRAY[@]}"; do
         # POSSIBLE CODE HERE
        done
      else
        addMXrecord  "$DNSNAME" "$DNSVALUE"
      fi

The function addMXrecord will be containing the JSON (although it's for a single MX record.)

DNSFILE is in format:

DOMAIN,MX,1 A
DOMAIN,MX,2 B

Happy to provide anymore information.

Upvotes: 1

Views: 3944

Answers (2)

chepner
chepner

Reputation: 531758

A jq filter for this would look like

TEMPARRAY=( "1 A" "2 B" )
printf '%s\n' "${TEMPARRAY[@]}" |
  jq --slurp -R '
    split("\n")[:-1] | map({Value: .}) |
    {
      Comment: "MX Record for XYZ",
      Changes: [
        {
          Action: "CREATE",
          ResourceRecordSet: {
            Name: "XYZ",
            Type: "MX",
            TTL: 300,
            ResourceRecords: .
          }
        }
      ]
    }
  '

split takes input lines and creates an array ["1 A", "2 B", ""] (the [:-1] gets rid of the final empty element due to the trailing newline from the input). map produces a corresponding array of objects [{"Value": "1 A"}, {"Value": "2 B"}]. The rest is just the template into which this array is inserted, as the value (represented by ., the input from map) to associate with the key ResourceRecords.

Upvotes: 2

AKX
AKX

Reputation: 169269

This doesn't sound like something you'd want to implement in Bash, to be honest!

Either way, if you already have most of your script implemented in Bash, you could use a tool like jq, or if you don't want the additional dependency, you could "shell out" to, for instance, Python:

python -c 'import json, sys; print(json.dumps([{"Value": v} for v in sys.argv[1:]]))' foo bar

will output

[{"Value": "foo"}, {"Value": "bar"}]

which you can embed elsewhere.

Upvotes: 0

Related Questions