如何使用jq将json数组转换为bash字符串数组? [英] How do I convert json array to bash array of strings with jq?

查看:97
本文介绍了如何使用jq将json数组转换为bash字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将对象的json数组解析为bash数组,并将这些对象作为字符串?

How do I parse a json array of objects to a bash array with those objects as strings?

我正在尝试执行以下操作:

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"}

,我需要将其传递给api:

and I need to pass it to an api:

api_call '{ "key1":"value1", "key2": "value2"}'

推荐答案

问题在于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

这篇关于如何使用jq将json数组转换为bash字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆