Tuesday, 23 June 2020

Convert json array of objects to bash associative array

{
"Parameters": [
    {
        "Name": "/path/user_management/api_key",
        "Type": "SecureString",
        "Value": "1234",
        "Version": 1
    },
    {
        "Name": "/path/user_management/api_secret",
        "Type": "SecureString",
        "Value": "5678",
        "Version": 1
    }
]
}

#!/usr/bin/env bash
# declare an associative array, the -A defines the array of this type
declare -A _my_Array

# The output of jq is separated by '|' so that we have a valid delimiter
# to read our keys and values. The read command processes one line at a 
# time and puts the values in the variables 'key' and 'value'
while IFS='|' read -r key value; do
    # Strip out the text until the last occurrence of '/' 
    strippedKey="${key##*/}"
    # Putting the key/value pair in the array
    _my_Array["$strippedKey"]="$value"
done< <(jq -r '.Parameters[] | "\(.Name)|\(.Value)"' json)

# Print the array using the '-p' or do one by one
declare -p _my_Array

No comments:

Post a Comment

How to check if a file contains a specific string using Bash

 In case if you want to check whether file does not contain a specific string, you can do it as follows. if ! grep -q SomeString "$File...