将JSON数组组织到菜单中

2exbekwf  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(92)

我从一个API中获得了以下数据:

[{"name":"***.com","id":"***-0a5864441f49","type":"NATIVE"},{"name":"***.de","id":"***-0a5864441f49","type":"NATIVE"},{"name":"***.com","id":"***-0a5864440f67","type":"NATIVE"},{"name":"***.de","id":"***-0a5864441314","type":"NATIVE"},{"name":"***.com","id":"***-0a586444968b","type":"NATIVE"},{"name":"***.de","id":"***-0a5864441314","type":"NATIVE"},{"name":"***.de","id":"***-0a5864441f49","type":"NATIVE"},{"name":"***.de","id":"***-0a5864441f49","type":"NATIVE"},{"name":"***.de","id":"***-0a58644406ac","type":"NATIVE"},{"name":"***.de","id":"***-0a58644435f4","type":"NATIVE"}]

字符串
我想创建一个菜单,像这样:

Choose one:
1. ***.com ***-0a5864441f49
2. ***.de ***-0a5864441f49
and so on...


然后我想进一步使用输入,在bash中,最有效的方法是什么?
我正在考虑一个数组,但我认为IFS不希望我使用},{作为数组,对吗?
我试过使用IFS,但没有成功。

0qx6xfy6

0qx6xfy61#

您可以使用jq将输入转换为如下所示(参见playground):

$ jq -r 'map("\(.name) \(.id)")[]' infile.json
***.com ***-0a5864441f49
***.de ***-0a5864441f49
***.com ***-0a5864440f67
***.de ***-0a5864441314
-->8--

字符串
在此基础上,您可以将此输出读取到数组中,然后使用select内置来呈现菜单:

readarray -t opts < <(jq -r 'map("\(.name) \(.id)")[]' infile.json)

PS3='Choose one: '
select opt in "${opts[@]}"; do
    echo "Do something with $opt"
    break
done


导致一个提示,

1) ***.com ***-0a5864441f49    6) ***.de ***-0a5864441314
2) ***.de ***-0a5864441f49     7) ***.de ***-0a5864441f49
3) ***.com ***-0a5864440f67    8) ***.de ***-0a5864441f49
4) ***.de ***-0a5864441314     9) ***.de ***-0a58644406ac
5) ***.com ***-0a586444968b   10) ***.de ***-0a58644435f4
Choose one:

相关问题