Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

Convert a JSON array to a bash array of strings

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

and I need to pass it to an api:

api_call '{ "key1":"value1", "key2": "value2"}'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...