将对象的json数组转换为bash关联数组

里克·贝克

我有一个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
    }
]
}

我知道我需要使用jq和sed,但是我只是无法完全找到自己想要的东西。需要去除“ / path / user_management /”并将其余的设置为键,并使用“值”作为值。

试图找到一个相当干净的衬管命令。我想结束的是一个类似以下内容的bash关联数组:

myArray[api_key]="1234"
myArray[api_secret]="5678"
伊尼安

要求单行代码和要求不可读的代码一样好。如果要以适当的方式执行此操作,请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

或打印阵列,传统方式

for key in "${!_my_Array[@]}"; do 
    printf '%s %s\n' "${key}" "${_my_Array[$key]}"
done

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章