在 Bash 中访问 JSON 对象 - 关联数组/列表/另一个模型 [英] Accessing a JSON object in Bash - associative array / list / another model
问题描述
我有一个以 JSON 格式获取数据的 Bash 脚本,我希望能够将 JSON 转换为可访问的结构 - 数组/列表/或其他易于解析嵌套的模型数据.
I have a Bash script which gets data in JSON, I want to be able to convert the JSON into an accessible structure - array / list / or other model which would be easy to parse the nested data.
示例:
{
"SALUTATION": "Hello world",
"SOMETHING": "bla bla bla Mr. Freeman"
}
我想获得如下值:echo ${arr[SOMETHING]}
[ 不同的方法也是可选的.]
[ Different approach is optional as well. ]
推荐答案
如果你想要 key 和 value,并且基于 How do i将一个json对象转换成JQ中的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
中,只需将 jq
提供给 while
与 while ... do;...完成<<(command)
语法:
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
这篇关于在 Bash 中访问 JSON 对象 - 关联数组/列表/另一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!