4

I have an array of json objects that I'd like to convert to an associative array in bash with a slight alteration to the key

{
"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
    }
]
}

I know I need to use jq and sed but I just can't quite find the proper combination of doing what I'm looking for. Need to strip out "/path/user_management/" and set the remaining as the key, and use Value for value.

Trying to find a fairly clean one liner piping commands together. What I'd like to end up with is a bash associative array of something like:

myArray[api_key]="1234"
myArray[api_secret]="5678"
2
  • It certainly does on my linux environment so I accepted the answer. Doesn't work on my mac, so I'll have to work through that. Appreciate the help. Commented Sep 6, 2018 at 12:00
  • see also JSON array to bash variables using jq Commented Feb 7, 2024 at 19:21

1 Answer 1

5

Asking for a one-liner code is as good as asking for unreadable code. If you want do this in a proper way, read the output of jq command in a while loop and strip out unwanted characters as required.

#!/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

Or print the array, the traditional way

for key in "${!_my_Array[@]}"; do 
    printf '%s %s\n' "${key}" "${_my_Array[$key]}"
done
Sign up to request clarification or add additional context in comments.

2 Comments

Why do the opening parentheses in the last jq filter have to be escaped but not the closing ones?
@stefanct: it is string interpolation - jqlang.github.io/jq/manual/#string-interpolation allowing you to run filters within double quotes, causing the filter outputs to be treated as strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.