且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用jq将json数组转换为bash字符串数组?

更新时间:2023-01-17 19:12:11

问题在于jq仍仅输出文本行; 您不必将每个数组元素都保留为一个单元.也就是说,只要换行符在任何对象中都不是有效字符,您仍然可以在单独的行中输出每个对象.

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.

get_json_array | jq -c '.[]' | while read object; do
    api_call "$object"
done

当然,在这种假设下,您可以在bash 4中使用readarray命令来构建数组:

Of course, under that assumption, you could use the readarray command in bash 4 to build an array:

readarray -t conversations < <(get_json_array | jq -c '.[]')
for conversion in "${conversations[@]}"; do
    api_call "$conversation"
done