我有一个 json 对象数组,我想将其转换为 bash 中的关联数组,并对键稍加修改
{
"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
}
]
}
Run Code Online (Sandbox Code Playgroud)
我知道我需要使用 jq 和 sed,但我只是找不到执行我正在寻找的操作的正确组合。需要去掉“/path/user_management/”并将剩余的设置为key,并使用Value作为value。
试图找到一个相当干净的一衬管管道命令在一起。我想要最终得到的是一个 bash 关联数组,如下所示:
myArray[api_key]="1234"
myArray[api_secret]="5678"
Run Code Online (Sandbox Code Playgroud)
要求单行代码与要求不可读的代码一样好。如果您想以正确的方式执行此操作,请jq在 while 循环中读取命令的输出,并根据需要删除不需要的字符。
#!/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
Run Code Online (Sandbox Code Playgroud)
或者以传统方式打印数组
for key in "${!_my_Array[@]}"; do
printf '%s %s\n' "${key}" "${_my_Array[$key]}"
done
Run Code Online (Sandbox Code Playgroud)