JSON列表(不是对象)到Bash数组? [英] JSON list (not object) to Bash array?

查看:100
本文介绍了JSON列表(不是对象)到Bash数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON列表(包含项列表的键/值对的值):

I've got a JSON list (the value of a key-value pair containing a list of items):

[ "john", "boris", "joe", "frank" ]

如何将其转换为bash数组,以便可以对其进行迭代?

How would I convert this to a bash array, so I can iterate over them?

推荐答案

简单案例:无换行符的字符串

简单的方法是使用 jq 将您的列表转换为每行-item,并将其读入脚本:

Easy Case: Newline-Free Strings

The simple approach is to use jq to transform your list into a line-per-item, and read that into your script:

json='[ "john", "boris", "joe", "frank" ]'
readarray -t your_array < <(jq -r '.[]' <<<"$json")
declare -p your_array

...正确发射:

declare -a your_array=([0]="john" [1]="boris" [2]="joe" [3]="frank")


棘手的情况:带换行符的字符串

有时,您需要读取可能包含换行符的字符串(或希望避免由于将恶意或格式错误的数据读入错误的字段而导致的安全风险).为了避免这种情况,您可以在数据之间使用NUL分隔符(并删除其中包含的所有NUL值):


Tricky Case: Strings With Newlines

Sometimes you need to read strings that can contain newlines (or want to avoid security risks caused by malicious or malformed data being read into the wrong fields). To avoid that, you can use NUL delimiters between your data (and remove any NUL values contained therein):

json='[ "john\ndoe", "marco\nquent", "malicious\u0000data" ]'

array=( )
while IFS= read -r -d '' item; do
  array+=( "$item" )
done < <(jq -j '.[] | ((. | sub("\u0000"; "<NUL>")) + "\u0000")' <<<"$json")

declare -p array

...正确发射:

declare -a array=([0]=$'john\ndoe' [1]=$'marco\nquent' [2]="malicious<NUL>data")

...和printf '<%s>\n\n' "${array[@]}"正确发出:

<john
doe>

<marco
quent>

<malicious<NUL>data>

(请注意,非常新的bash具有readarray -0,可以避免需要上面给出的while IFS= read -r -d ''循环,但这并不常见.还请注意,您可以使用该循环直接遍历,而不需要首先将内容存储在数组中;请参阅 BashFAQ#1 ).

(Note that very new bash has readarray -0, which can avoid the need for the while IFS= read -r -d '' loop given above, but that's not common yet. Also note that you can use that loop to directly iterate over content from jq, avoiding the need to store content in an array in the first place; see BashFAQ #1).

这篇关于JSON列表(不是对象)到Bash数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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