我有一个来自API请求的字符串,看起来像大json,每个元素都有2个字段(名称,href(,在此操作之后,我将这个名称添加到数组中:
str_from_api="$(user_groups_json "limit=100" | jq -r '.items | .[].name')"
readarray -t usergroups_array <<< "$str_from_api"
但是我需要在数组usergroups_array中存储 2 个变量(名称和 href(。我的意思是下一个解决方案:
数组:
str_from_api=(name:"Test name", href: "Test href")
此数组将很长,有 100 条记录。在我需要对每个名称和每个 href 进行操作之后,这就是为什么我需要访问此结构的每个元素的原因。
我该如何实现?
更新
杰森:
{
"totalCount": 2,
"items": [
{
"name": "test name",
"active": false,
"createdFrom": "SAML",
"_meta": {
"allow": [
"DELETE",
"GET",
"PUT"
],
"href": "https://href2.com"
}
},
{
"name": "test name 2",
"active": false,
"createdFrom": "SAML",
"_meta": {
"allow": [
"DELETE",
"GET",
"PUT"
],
"href": "https://href1.com"
}
}
]
这是一个快速而肮脏的尝试,可以在 Bash 循环中获取输出。
user_groups_json "limit=100" |
jq -r '.items | .[] | (._meta.href + " " + .name)' |
while read -r href name; do
echo "'$name' has href '$href'"
: do stuff with these variables here
done
你说你想要在一个数组中,但随后解释说你希望一次处理一个;所以将整个列表存储在一个你只访问一次的变量中似乎是多余的。