从json获取字段并分配给bash脚本中的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22528142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get field from json and assign to variable in bash script?
提问by user3441187
I have a json store in jsonFile
我在 jsonFile 中有一个 json 存储
{
"key1": "aaaa bbbbb",
"key2": "cccc ddddd"
}
I have code in mycode.sh:
我有代码mycode.sh:
#!/bin/bash
value=($(jq -r '.key1' jsonFile))
echo "$value"
After I run ./mycode.shthe result is aaaabut if I just run jq -r '.key1' jsonFilethe result is aaaa bbbbb
我运行后./mycode.sh的结果是aaaa但如果我只是运行jq -r '.key1' jsonFile结果是aaaa bbbbb
Could anyone help me?
有人可以帮助我吗?
回答by Saucier
With that line of code
用那行代码
value=($(jq -r '.key1' jsonFile))
you are assigning both values to an array. Note the outer parantheses ()around the command.
Thus you can access the values individually or echo the content of the entire array.
您正在将两个值分配给一个数组。请注意()命令周围的外部括号。因此,您可以单独访问值或回显整个数组的内容。
$ echo "${value[@]}"
aaaa bbbb
$ echo "${value[0]}"
aaaa
$ echo "${value[1]}"
bbbb
Since you echoed $valuewithout specifying which value you want to get you only get the first value of the array.
由于您在$value没有指定要获取的值的情况下进行回显,因此您只能获取数组的第一个值。

