将 JSON 数组转换为字符串的 bash 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35005893/
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
Convert a JSON array to a bash array of strings
提问by Ela
How do I parse a json array of objects to a bash array with those objects as strings?
如何将对象的 json 数组解析为将这些对象作为字符串的 bash 数组?
I am trying to do the following:
我正在尝试执行以下操作:
CONVO=$(get_json_array | jq '.[]')
for CONVERSATION in $CONVERSATIONS
do
echo "${CONVERSATION}"
done
But the echo prints out lines instead of the specific objects. The format of the object is:
但是回声打印出线条而不是特定对象。对象的格式为:
{ "key1":"value1", "key2": "value2"}
and I need to pass it to an api:
我需要将它传递给一个 api:
api_call '{ "key1":"value1", "key2": "value2"}'
回答by chepner
The problem is that jq
is still just outputting lines of text; you can't necessarily preserve each array element as a single unit. That said, as long as a newline is not a valid character in any object,you can still output each object on a separate line.
问题是jq
仍然只是输出文本行;您不一定将每个数组元素保留为一个单元。也就是说,只要换行符不是任何对象中的有效字符,您仍然可以在单独的行上输出每个对象。
get_json_array | jq -c '.[]' | while read object; do
api_call "$object"
done
Of course, under that assumption, you could use the readarray
command in bash
4 to build an array:
当然,在这种假设下,您可以使用4 中的readarray
命令bash
来构建数组:
readarray -t conversations < <(get_json_array | jq -c '.[]')
for conversion in "${conversations[@]}"; do
api_call "$conversation"
done