将对象的json数组转换为bash关联数组
我有一个json对象数组,我想在bash中将其转换为一个关联数组,只需稍微修改一下键将对象的json数组转换为bash关联数组,bash,jq,Bash,Jq,我有一个json对象数组,我想在bash中将其转换为一个关联数组,只需稍微修改一下键 { "Parameters": [ { "Name": "/path/user_management/api_key", "Type": "SecureString", "Value": "1234", "Version": 1 }, { "Name": "/path/user_management/api_
{
"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
}
]
}
我知道我需要使用jq和sed,但我就是找不到合适的组合来完成我想要的任务。需要去掉“/path/user\u management/”并将剩余的设置为键,并使用Value作为Value
试图找到一个相当干净的单内衬管道。最后,我希望得到一个bash关联数组,它类似于:
myArray[api_key]="1234"
myArray[api_secret]="5678"
要求一行代码和要求不可读的代码一样好。如果希望以正确的方式执行此操作,请在while循环中读取
jq
命令的输出,并根据需要去除不需要的字符
#!/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
在我的linux环境中确实如此,所以我接受了答案。在我的mac电脑上不起作用,所以我必须解决这个问题。谢谢你的帮助。
for key in "${!_my_Array[@]}"; do
printf '%s %s\n' "${key}" "${_my_Array[$key]}"
done