有没有办法读取JSON文件中的所有键值对,然后在shell中相应地初始化所有变量? [英] Is there a way to read all key-value pairs in the JSON file and then initialize all variables accordingly in shell?
本文介绍了有没有办法读取JSON文件中的所有键值对,然后在shell中相应地初始化所有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个JSON文件arguments.json
:
Given a JSON file, arguments.json
:
{"dagger": true, "version": false, "nether_strike": true,
"greater_bash": "5", "FILE": "ancientscroll.txt",
"empower_haste": "1", "help": false}
我可以在外壳中使用jq
进行读取,并分别初始化变量:
I can read using jq
in shell and initialize the variables individually:
dagger=$(cat arguments.json | jq '.["dagger"]')
greater_bash =$(cat arguments.json | jq '.["greater_bash"]')
echo $dagger
echo $greater_bash
是否可以读取JSON文件中的所有键值对,然后在shell中相应地初始化所有变量?
推荐答案
您可以遍历键/值对,并使用declare
动态创建变量名.
You can loop over the key/value pairs and use declare
to create variable names dynamically.
while read -r name value; do
declare "$name=$value"
done < <(jq -r 'to_entries[] | "\(.key) \(.value)"' arguments.json)
这篇关于有没有办法读取JSON文件中的所有键值对,然后在shell中相应地初始化所有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文