[英]convert JSON array to bash array preserving whitespaces
I want to transform JSON file into bash array of strings that i will later be able to iterate over.我想将 JSON 文件转换为 bash 字符串数组,稍后我将能够对其进行迭代。 My JSON structure is as follows:我的 JSON 结构如下:
[
{
"USERID": "TMCCP",
"CREATED_DATE": "31/01/2020 17:52"
},
{
"USERID": "TMCCP",
"CREATED_DATE": "31/01/2020 17:52"
}
]
And this is my bash script:这是我的 bash 脚本:
test_cases=($(jq -c '.[]' data.json))
echo ${test_cases[0]}
echo ${test_cases[1]}
echo ${test_cases[2]}
echo ${test_cases[3]}
As you can see it returns array with 4 elements instead of 2. Output:如您所见,它返回包含 4 个元素而不是 2 个元素的数组。Output:
{"USERID":"TMCCP","CREATED_DATE":"31/01/2020
17:52"}
{"USERID":"TMCCP","CREATED_DATE":"31/01/2020
17:52"}
For some reason having whitespace in date field causes some parsing issues.出于某种原因,在日期字段中有空格会导致一些解析问题。 Any idea how to get over this?知道如何克服这个问题吗?
Use readarray
instead.请改用readarray
。
$ readarray -t test_cases < <(jq -c '.[]' file)
$ declare -p test_cases
declare -a test_cases=([0]="{\"USERID\":\"TMCCP\",\"CREATED_DATE\":\"31/01/2020 17:52\"}" [1]="{\"USERID\":\"TMCCP\",\"CREATED_DATE\":\"31/01/2020 17:52\"}")
And read
can be used as shown below where readarray
is unavailable.并且read
可以在readarray
不可用的地方如下所示使用。
IFS=$'\n' read -d '' -a test_cases < <(jq -c '.[]' file)
Use readarray
to populate the array, rather than using an unquoted command substitution;使用readarray
填充数组,而不是使用不带引号的命令替换; bash
doesn't care about JSON quoting when it splits the result into separate words. bash
在将结果拆分为单独的单词时不关心 JSON 引用。
readarray -t test_cases < <(jq -c '.[]' data.json)
In bash
3.2 (which is what you appear to be stuck with), you need something slightly more unwieldy在bash
3.2 中(这似乎是你所坚持的),你需要一些更笨拙的东西
while IFS= read -r line; do
test_cases+=("$line")
done < <(jq -c '.[]' data.json)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.