将JSON对象数组转换为Bash关联数组

3
我有一个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/”,并将其余部分设置为键,使用Value作为值。

试图找到一个相当干净的一行命令进行管道连接。我想最终得到的是一个bash关联数组,例如:

myArray[api_key]="1234"
myArray[api_secret]="5678"

在我的Linux环境中确实可以,所以我接受了这个答案。在我的Mac上不起作用,所以我需要解决这个问题。感谢您的帮助。 - Rick Baker
1个回答

6

要求一行代码是等同于要求难以阅读的代码。如果您希望以正确的方式执行此操作,请在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

或者按传统方式打印数组。
for key in "${!_my_Array[@]}"; do 
    printf '%s %s\n' "${key}" "${_my_Array[$key]}"
done

为什么最后一个 jq 过滤器中的开括号需要转义,而闭括号不需要呢? - undefined
1
@stefanct: 这是字符串插值 - https://jqlang.github.io/jq/manual/#string-interpolation 允许您在双引号内运行过滤器,使过滤器的输出被视为字符串。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接