将JSON对象转换为Bash关联数组 [英] Converting a JSON object into a Bash associative array
问题描述
我有一个Bash脚本.它以JSON格式获取数据. 我需要将JSON数组转换为Bash数组.
I have a Bash script. It gets data in JSON. I need to convert the JSON array to a Bash array.
示例
{
"SALUTATION": "Hello world",
"SOMETHING": "bla bla bla Mr. Freeman"
}
在Bash中,我想要一个类似echo ${arr[SOMETHING]}
的值.
In Bash I want to get a value like this echo ${arr[SOMETHING]}
.
推荐答案
如果您想要键和值,并且基于我如何将JQ中的json对象转换为key = value格式,您可以执行以下操作:
If you want key and value, and based on How do i convert a json object to key=value format in JQ, you can do:
$ jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" file
SALUTATION=Hello world
SOMETHING=bla bla bla Mr. Freeman
以更一般的方式,您可以像这样将值存储到数组myarray[key] = value
中,只需使用while ... do; ... done < <(command)
语法为while
提供jq
即可:
In a more general way, you can store the values into an array myarray[key] = value
like this, just by providing jq
to the while
with the while ... do; ... done < <(command)
syntax:
declare -A myarray
while IFS="=" read -r key value
do
myarray[$key]="$value"
done < <(jq -r 'to_entries|map("(.key)=(.value)")|.[]' file)
然后您可以遍历像这样的值:
And then you can loop through the values like this:
for key in "${!myarray[@]}"
do
echo "$key = ${myarray[$key]}"
done
对于此给定的输入,它将返回:
For this given input, it returns:
SALUTATION = Hello world
SOMETHING = bla bla bla Mr. Freeman
这篇关于将JSON对象转换为Bash关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!