convert JSON array to bash array preserving whitespaces

旧城冷巷雨未停 提交于 2021-02-05 11:39:53

问题


I want to transform JSON file into bash array of strings that i will later be able to iterate over. My JSON structure is as follows:

[
  {
    "USERID": "TMCCP",
    "CREATED_DATE": "31/01/2020 17:52"
  },
  {
    "USERID": "TMCCP",
    "CREATED_DATE": "31/01/2020 17:52"
  }
]

And this is my bash script:

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:

{"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?


回答1:


Use readarray instead.

$ 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.

IFS=$'\n' read -d '' -a test_cases < <(jq -c '.[]' file)



回答2:


Use readarray to populate the array, rather than using an unquoted command substitution; bash doesn't care about JSON quoting when it splits the result into separate words.

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

while IFS= read -r line; do
    test_cases+=("$line")
done < <(jq -c '.[]' data.json)


来源:https://stackoverflow.com/questions/62815281/convert-json-array-to-bash-array-preserving-whitespaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!